• I am trying to change an image source using jQuery. Now, when I try to use jQuery, I have only gotten an alert box to work. I can do everything perfectly in javascript, but jQuery just does not want to cooperate. jQuery is listed as a dependency and the fact that I can create an alert box means everything is registered and enqueued properly.

    I was just testing to see if I could make an alert when I click on a certain element, but no luck. Can anyone tell me what the error is in this code?

    This works:

    (function($){
    
    	alert("hello");
    
     }(jQuery));

    Next I tried to create an alert when I click an element with an Id selector. This does NOT work:

    (function($){
    
    	$('#slide-holder').on('click', function(){
    		alert("hello");
    	});	
    
     }(jQuery));

    Then I tried with a class selector. This also does NOT work:

    (function($){
    
    	$('.picture-place-holder').on('click', function(){
    		alert("hello");
    	});	
    
     }(jQuery));

    I checked and double checked to make sure my id and class match the element I want to add the event to, but WordPress seems to really not want me to use jQuery. I also do not have any plugins installed that use jQuery. Can anyone see the problem in my code??

Viewing 2 replies - 1 through 2 (of 2 total)
  • How are you enqueueing the script? If you place the script in the header, then the DOM won’t be ready when the script runs and the event won’t attach properly. You could call $( document ).ready() within the anonymous function itself:

    ( function( $ ) {
      $( document ).ready( function() {
        ... code goes here ...
      });
    
      .. other code goes here ...
    })(jQuery);
    Thread Starter brandonf

    (@brandonf)

    Thanks Stephen, your solution worked perfectly!

    In case anyone else has this problem

    In functions.php I have

    function sumcakes_scripts() {
    	wp_register_script('extrajs', get_template_directory_uri() . "/js/extra.js", array('jquery'));
    	wp_enqueue_script('extrajs');
    }
    
    add_action('wp_enqueue_scripts', 'sumcakes_scripts');

    and in my javascript file (in this case mine is called extrajs.js) I have the solution provided by stephencottontail above and my code inside. Thanks again stephen!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘I am only able to create an alert box in jQuery but Javascript works perfectly.’ is closed to new replies.