Dominic Fox
Dominic Fox

Reputation: 118

Calling a jQuery Function from within .click()

I am uncertain why this code is not functioning. The goal is to hide an image and show another one in its place when the user clicks .accent. The currently displayed image (which is shown on page load) is referenced by the class .ssi-hide.

Here is the jQuery:

    jQuery(document).ready(function($){
      // jQuery methods go here...

      var currentImage = '".ssi-hide"';

      $(".accent").click(function() {
         swapImage( currentImage, "#accent-img" );
      });
    }); //end jQuery

and here is the function:

    (function( $ ) {
        $.fn.swapImage = function( outPic, inPic ) {
            $( outPic ).fadeOut(200, function(){
            $( inPic ).fadeIn(400).css("display", "block").css("margin", "auto");
            });
            currentImage = inPic;
        };
    })( jQuery );

Chrome is notifying that: "Uncaught ReferenceError: swapImage is not defined" as well as "Uncaught Error: Syntax error, unrecognized expression: ".ssi-hide""

Thank you very much for any help.

Upvotes: 0

Views: 56

Answers (2)

Lennholm
Lennholm

Reputation: 7470

First, currentImage doesn't need two sets of quotes, use var currentImage = ".ssi-hide"; instead.

You're invoking the function as if it was a scoped function, but it's a jQuery plugin. instead of:

$(".accent").click(function() {
    swapImage( currentImage, "#accent-img" );
});

It ought to be:

$(".accent").click(function() {
    $(this).swapImage( currentImage, "#accent-img" );
});

But I don't see why you need to have it as a jQuery plugin since it doesn't use this anywhere.

Instead, it should really be defined as a class function

(function( $ ) {
    $.swapImage = function( outPic, inPic ) {
        $( outPic ).fadeOut(200, function(){
        $( inPic ).fadeIn(400).css("display", "block").css("margin", "auto");
        });
        currentImage = inPic;
    };
})( jQuery );

then you call

$(".accent").click(function() {
    $.swapImage( currentImage, "#accent-img" );
});

Upvotes: 3

Shabi Levi
Shabi Levi

Reputation: 258

Using onclick creates an attribute, and its value should be a string that refers to a function, not an actual function. Using click creates a property on the element, and its value should be the function itself.

jQuery(document).ready(function($){
          // jQuery methods go here...

          var currentImage = $(".ssi-hide");

          $(".accent").on("click",function() {
             $(this).swapImage( currentImage, "#accent-img" );
          });
        }); //end jQuery

Upvotes: 0

Related Questions