0

this is the code that i wrote:-

for (let i = 1; i < 10; i++) {
var sfq = ".main-head"+[i];
console.log(sfq);
$(sfq).mouseover(function(){
    $(sfq).addClass("colorChangeOnMouseOver");
    setTimeout(function(){$(sfq).removeClass("colorChangeOnMouseOver")},500);
})
}

The desired output:-

//$(".main-head1").mouseover(function(){
    //     $(".main-head1").addClass("colorChangeOnMouseOver");
    //     setTimeout(function(){$(".main-head1").removeClass("colorChangeOnMouseOver")},500);
// });
// $(".main-head2").mouseover(function(){
    //     $(".main-head2").addClass("colorChangeOnMouseOver");
    //     setTimeout(function(){$(".main-head2").removeClass("colorChangeOnMouseOver")},500);
// });

and so on... I can understand why it doesn't work but is there a way around it?

2 Answers2

0

You might want to convert the sfq variable into a let variable so from inside the setTimeout, the value referred is correct.

Right now all the functions inside setTimeout will refer to the same one value of sfq which is .main-head9.

Also, [] no need to use this.

for (let i = 1; i < 10; i++) {
let sfq = ".main-head"+i;
console.log(sfq);
$(sfq).mouseover(function(){
    $(this).addClass("colorChangeOnMouseOver");
    setTimeout(function(){$(sfq).removeClass("colorChangeOnMouseOver")},500);
})
}
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
0

You can do it like this:

$("[class*=main-head]").mouseenter(function() {
  var $this = $(this);
  $this.addClass("colorChangeOnMouseOver");
  
  setTimeout(function() {
    $this.removeClass("colorChangeOnMouseOver")
  }, 500);
});

class*=main-head means that it will select all elements that has a class that contains main-head

Demo

$("[class*=main-head]").mouseenter(function() {
  var $this = $(this);
  $this.addClass("colorChangeOnMouseOver");
  
  setTimeout(function() {
    $this.removeClass("colorChangeOnMouseOver")
  }, 500);
});
.colorChangeOnMouseOver{
color:red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test main-head1">main-head1</div>


<div class="main-head1">main-head2</div>


<div class="main-head1">main-head3</div>
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77