red house 87
red house 87

Reputation: 2415

Jquery add class not working?

Here is my jQuery:

$('.portfoliopod').on('click', function(){
    $('.portfoliopod').addClass('current');
});

and my HTML:

<div class="portfoliopod">
<img class="portfolioimage" src="aboutme.jpg">
<div class="portfoliopodmessage">testing 123</div>
</div>

When I click the "portfolio pod" section the class "current" is not added. Am i missing something obvious here?

Upvotes: 0

Views: 54

Answers (2)

Subin
Subin

Reputation: 3563

As OP said "on click of a button the portoflio is loaded through PHP", I assume the portfolio content is loaded via AJAX. So, you have to use this to listen the event on the element :

jQuery(document).on('click', '.portfoliopod', function(){
    jQuery('.portfoliopod').addClass('current');
});

As the .portfoliopod element is a dynamically created element, the code you're currently using won't bind the event to element that is going to come in the DOM tree later.

So, the way of binding the listener is to bind it on document and check if the element clicked on document is .portfoliopod. See this.

Also, it seems like on your site, $ is undefined (very strange). So, use jQuery instead.

Or, if you want the $ object, add this code at the very end of your jQuery file before })(window); :

window.jQuery = window.$ = jQuery;

Upvotes: 1

Sarath Kumar
Sarath Kumar

Reputation: 2353

check it by using this code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="portfoliopod">
<img class="portfolioimage" src="aboutme.jpg">
<div class="portfoliopodmessage">testing 123</div>
</div>
<script>
$('.portfoliopod').on('click', function(){
    $('.portfoliopod').addClass('current');
});</script>

if this code works then , the fault is with the inclution of jquery script.

Upvotes: 0

Related Questions