-1

How do i detect a special class in a child div and a when the specific class is found add a class into a other div?

Example:

 <ul class="m-a-ul">
    <li class="menu">
 </ul>

Now the specific class collapsed is added through an action:

 <ul class="m-a-ul">
    <li class="menu collapsed">
 </ul>

A script should now detect that a child of the ul m-a-ul got added a class named collapsed. Now the class darken should be added to a other div with the ID content:

<div id="content" class="darken">
...
</div>

And now, when the class collapsed disapears the class darken should also be removed

Ive tried this Code:

<script>
$(document).ready(function(){
    $(".menu").click(function(){
        $("#content").addClass("darken");
    });
});
</script>

That adds the class darken when a button is clicked. But that was the wrong solution. I need one that add the class only when a class is found in a specific div.

1 Answers1

1

You can try

if(jQuery('.m-a-ul .menu').hasClass('collapsed')){
     jQuery('#content').addClass('darken');
   }else{
     jQuery('#content').removeClass('darken');
   }
Bai Nguyen
  • 814
  • 7
  • 16
  • Does not seem to work: https://www.w3schools.com/code/tryit.asp?filename=FOVX5NZZKIKO – hippolas_cage Feb 28 '18 at 01:47
  • You must add javascript after html https://www.w3schools.com/code/tryit.asp?filename=FOVX8Z3FTP0I or add in jQuery(document).ready(function(){ // code in here }) – Bai Nguyen Feb 28 '18 at 01:51
  • I there any possibility to execute the script also after the page is already loaded? I mean when the class "collapsed" is added afterwords – hippolas_cage Feb 28 '18 at 02:03
  • So i think you need add it in a action https://www.w3schools.com/code/tryit.asp?filename=FOVXWTFKZLXQ – Bai Nguyen Feb 28 '18 at 02:14