0

I am having trouble implementing the jQuery .addClass() effect.

The script I am trying to use looks like this:

<script>
    $(function(){   
        $('#top_right_size_large').click(function(){
            $('#primary').addClass('large_content');
        });
    });
    </script>

I've looked at the documentation and checked all of my parenthesizes but for whatever reason this doesn't add the .large_content class when the #top_right_size_large anchor is clicked. Any ideas why this wouldn't work the way I expect it to?

3
  • How do you know it is not added? Did you have a look at the DOM? Do the elements with ID primary or top_right_size_large exists? Your code works fine: jsfiddle.net/fkling/wcTz5 so I assume your HTML is not correct or adding the class just does not change anything visually. Commented Apr 29, 2011 at 7:51
  • Yeah, they all exist - there aren't any typos. I know its not getting added because I am watching with firebug. Plus, there aren't any of the styles associated with that class being applied. Commented Apr 29, 2011 at 7:52
  • 1
    See my edit. Your code works fine: jsfiddle.net/fkling/wcTz5 Could you provide a link to the page? Or post the HTML? Commented Apr 29, 2011 at 7:54

3 Answers 3

1

Just a guess, your anchor has an href and when clicked, it reloads the page, try changing code like below:

<script>
    $(function(){   
        $('#top_right_size_large').click(function(e) {
            e.preventDefault();
            $('#primary').addClass('large_content');
        });
    });
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Thats a good guess, I always forget to change the href thing.
@Thomas: Even better: If you don't use the link as link, meaning it does not refer to another site, use a button.
0

Apparently, by adding the code before the tag, the script wouldn't work. I moved the code below the tag and everything works fine. Thanks for all the suggestions!

3 Comments

It should work, because you are passing a callback to the document.ready event. I.e. the code is run after the DOM is loaded. Or maybe this is not the code you have? In my jsfiddle example you can see that the code is added to the head of the page (i.e. before the elements) and it works.
I didn't use document.ready - thats why it needed to be loaded after the content. Thanks for helping me flush it out.
Well, in your code you do. $(function(){...}) is a shortcut for $(document).ready(function(){...}). But anyway....
0

Include javascript:void(0); in your href to prevent any navigation

<a id="op_right_size_large" href="JAVASCRIPT:VOID(0);">..</a>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.