Where correctly declare a function jQuery

Viewed 36

I want to declare a function and use it into other functions. In this example the called function shows the alert but doesn't change the background color. But if I declaire the function inside the $('.box').click(function() {... then it works properly.

What am I doing wrong? How can I declaire a function globally?

$(document).ready(function() {

   function changeColor() {
      $(this).css('background-color','red');
      alert('Color changed!');
  }
  
  $('.box').click(function() {
   changeColor();
  })
});
.box {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>

4 Answers

You need to pass the object of the .box. The function you are calling will not get he object of .box using the $(this) that's why you need to pass the this object on the function.

$(document).ready(function() {

   function changeColor(that){
      $(that).css('background-color','red');
      alert('Color changed!');
  }
  
  $('.box').click(function() {
   changeColor(this);
  })
});
.box {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>

Hope this will be helpful to you.

to use function outside of click event, you should pass this as parameter.

   function changeColor($this) {
      $($this).css('background-color','red');
      alert('Color changed!');
  }


  $('.box').click(function() {
    changeColor(this);
  })

If you call changeColor like this then context this is going to be global object window, not what you want.

Simple solution would be to pass pass element into the function as parameter:

$(document).ready(function() {

  function changeColor(element) {
    $(element).css('background-color', 'red');
    console.log('Color changed!');
  }

  $('.box').click(function() {
    changeColor(this);
  })
});
.box {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>

Just pass the function as event handler directly or make it anonymous, otherwise the $(this) will be the window and not the element

$(document).ready(function() {

  function changeColor() {
    $(this).css('background-color', 'red');
    alert('Color changed!');
  }

  $('.box').click(changeColor)
});
.box {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>

Related