Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

303
Views
i wanted to select .main-head(1-9) and carry out a function

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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);
})
}
about 4 years ago · Juan Pablo Isaza Report

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!