Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: "addClass doesn't work by id", when document ready

I have a problem, and try it to solve two more days. Try do it like this:

$.when( $(document).ready ).then(function func_fold () {
  $( "#collapsible_sidebar" ).addClass('folded');    
})

And like this:

$(document).ready(function func_fold () {
  $( "#collapsible_sidebar" ).addClass('folded');    
})

And like this too:

$(document).ready(function() {
  $( "#collapsible_sidebar" ).addClass('folded');    
})

Try .hide() to see work selector at all, and it doesn't work too. But when I open DOM, I can see this element and this ID.

Warning! I think it important, this div is added to DOM by AJAX.

HTML element:

<div id="collapsible_sidebar"><?php dynamic_sidebar( 'sidebar-1' ); ?></div>
like image 261
Georgy Potapov Avatar asked Mar 08 '19 17:03

Georgy Potapov


1 Answers

If it's being added to the DOM by AJAX, that means it's being added sometime after $(document).ready(). AJAX stands for "Asynchronous Javascript And XML", asynchronous meaning that it will execute on its own time when the server can get to it. If you want to execute that class being added, you need to put $("#collapsible_sidebar").addClass('folded'); into the success function in your AJAX call.

$.ajax({
    //other parameters
    success: function () {
        $("#collapsible_sidebar").addClass('folded');
    }
});
like image 117
el toro Avatar answered Nov 18 '22 05:11

el toro