Home > Enterprise >  i wanted to select .main-head(1-9) and carry out a function
i wanted to select .main-head(1-9) and carry out a function

Time:10-01

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?

CodePudding user response:

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

CodePudding user response:

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);
})
}
  • Related