-6

Surely the answer to this is simple but I can't explain it so I ask it here.

https://jsbin.com/tuzifobale/edit?html,css,js,output

I'm trying to make a div have class added when you click on it and if the div has that class it then X function (in this case it's fadeout) happens, thus clicking on it makes X function happen.

How does chronology work in Javascript? Are there any links for reading I can get that can make me understand when and how things become applicable? Thanks.

Anand G
  • 3,130
  • 1
  • 22
  • 28
NateDogg
  • 11
  • 3

2 Answers2

2

welcome to StackOverflow.

You should take more precautions when writing your question, and make sure that it is written in good English, and in a way so that someone who does not priorly know what you want to achieve can understand your goal when reading the question.

I'm gonna try to answer to the parts I think I understand.

if the div has that class it then X function (in this case it's fadeout) happens

What I understand is that you would like to trigger the execution of function X when the <div> receives a class (clicked?).

Watching a DOM element's class value changes in Javascript is a problem that doesn't seem to have a reliable solution. (See related questions.)

thus clicking on it makes X function happen.

Maybe your goal is actually simpler. If you only want to trigger the execution of a function when you click on the <div>, then you'll have to look at mouse event handlers, especially .click() that allows to

Bind an event handler to the "click" JavaScript event

Community
  • 1
  • 1
David Stosik
  • 879
  • 9
  • 17
0

Few things I found in you JsBin are as below,

  1. Always include js files in Head or before element get loaded like below

  2. You can not find, if element is click or event is triggered in if condition like you did in for loop

  3. What is there in else?

See below and check if it helps you

$(document).ready(function(){
    $('div').animate({left:'200px'});
    $('div').animate({top:'200px'});  
    $('div').animate({left:'px'});
    $('div').animate({top:'-100px'});
    $('div').animate({top:'200px'});
    $('div').animate({left:'0px'});
    $('div').animate({top:'0px'});
  
     $('div').on('click', function(){
       $(this).addClass('clicked'); 
       $(this).stop(); //Stop animation
    });

});
div {width:100px; height:100px; background:red; position:relative}
.clicked {
  
  background: green;
  
}
<!DOCTYPE HTML>

<html>
  <head>

    <title></title>
      <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  </head>
  
  <body>    
    
    <div></div>
    
  </body>
</html>
Anand G
  • 3,130
  • 1
  • 22
  • 28