Reputation: 632
Problem: I can't remove a class previously added via jQuery.
The situation is the following, I have a div where ajax content appears.
When the link is clicked, #ajax_wrapper fades in.
This works. The Ajax loaded post content is loaded inside the div I have created: #ajax_wrapper. It holds inside the content, this content is loaded using a plugin called Essential Grid.
My customization is to create a wrapper to display the content in a personalized way.
jQuery(document).ready(function($) {
$('.eg-ajax-a-button').on('click', function() {
$('#ajax_wrapper').toggleClass('displayon');
});
Inside the Ajax content divs, managed by essential grid, there is a X (close link) to close the ajax loaded content. This works fine with the ajax content, but the wrapper, remains, over all the content.
I try to listen the X close link, so when it is clicked also it removes / toggles the class .displayon previously added to #ajax_wrapper.
I cannot seem to do it right. Nothing happens when I click the .eg-ajax-closer-wrapper. Is this because it is inside ajax loaded div?
This is what I have tried
jQuery(document).ready(function($) {
$('.eg-ajax-closer-wrapper').on('click', function() {
$('#ajax_wrapper').toggleClass('displayon');
});
});
The HTML looks like this:
<div id="ajax_wrapper" class="displayon">
<div class="eg-ajax-target-container-wrapper " id="sp-content-ajax">
<!-- CONTAINER FOR PREFIX -->
<div class="eg-ajax-target-prefix-wrapper">
</div>
<!-- CONTAINER FOR CONTENT TO LOAD -->
<div class="eg-ajaxanimwrapper" style="position: relative; overflow: hidden; height: auto; z-index: 0; min-height: 0px; max-height: none;"><div class="eg-ajax-target" style="visibility: inherit; opacity: 1; height: auto;"><div class="eg-ajax-closer-wrapper eg-acp-tr eg-acp-light eg-acp-type1"><div class="eg-ajax-closer eg-ajax-navbt">X</div></div><h2>Title sample</h2>
<p>Lorem Ipsum is simply dummy.</p>
</div></div>
<!-- CONTAINER FOR SUFFIX -->
<div class="eg-ajax-target-suffix-wrapper">
</div>
</div>
</div>
Upvotes: 0
Views: 116
Reputation: 74738
I guess you need event delegation:
$(document).on('click', '.eg-ajax-closer-wrapper', function() {
$('#ajax_wrapper').toggleClass('displayon');
});
The thing is, your content is loaded way after page load, so the event binding on static elements have been done because they were there in the DOM.
But the content was not there thus event on your target element not bound. This is the situation where we need to delegate the event to either static parent or to document
as this is always available.
Upvotes: 1
Reputation: 129802
When you're adding a listener to an element on DOMReady, you're only adding it to the elements matched by your selector at that instant.
If after your AJAX request you add new elements to the document, these will not automatically listen to the event.
To this end you will need to use event delegation (see "Direct and delegated events")
Upvotes: 0