I don't understand $(this)

I’m wondering how it works. I would like to use $(this) to do two things. In the script below, only the first one executes. The rest of the script is ignored.

$("#groups").delegate("a", "click", function() {
		window.location.hash = $(this).attr("href");
		$("#groups a").removeClass('active');

         // if the .addClass line below is not commented out, the rest of the script is ignored.
		$(this).addClass('active');
		
		// find the new page name by class
		var pageName = $(this).attr('class');
		
		// switch the bg in the css
		$("html").css("background-image","url(images/" + pageName + ".jpg)");
		
		return false;
	});

Your help is greatly appreciated, as always!

Are you certain it is being ignored. It looks to me like you assign a class to the hyperlink, then use the class to change the background image. If your links already have a class then you will end up with a class attribute that contains the word ‘active’ along with white space and other class names, which will break what you are trying to do with the background image.

In the call back of many jQuery functions ‘this’ refers to each element in the collection. Using $(this) means that you are creating a jQuery object out of the individual element, in your case this means the hyperlink. By doing that you can use all of the jQuery functions to do neat things, like adding the class.

There is a simple way to fix your code, I believe. Try:


$("#groups").delegate("a", "click", function() {
        window.location.hash = $(this).attr("href");
        $("#groups a").removeClass('active');
       
        // find the new page name by class
        var pageName = $(this).attr('class');
       
        // switch the bg in the css
        $("html").css("background-image","url(images/" + pageName + ".jpg)");

        // Moved the assignment of the active class below the css background change
        $(this).addClass('active');        

        return false;
    });

There would be a better way of achieving the same outcome here and that is to use a CSS class to hold the image information instead of changing the background image url via javascript.

Thanks for this. Nice explanation of what was going on. Moving the .addClass(‘active’) to the bottom works fine, as expected. I see now that by adding ‘active’ to the element first, then trying to call the bg image based on the class name of the element, it made no sense.