stack
stack

Reputation: 10218

How can I make an element on hover?

All I'm trying to do is something like this mechanism:

enter image description here

Here is what I've tried so far:

$(document).ready(function(){
    $('a').bind('mouseenter', function() {
      var self = $(this);
      this.iid = setInterval(function() {
      	 var tag_name = self.text(),
             top      = self.position().top + self.outerHeight(true),
             left     = self.position().left;
         self.append("<div class='tag_info'>Some explanations about"+tag_name+"</div>")
         $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);   
      }, 525);
		}).bind('mouseleave', function(){
    	this.iid && clearInterval(this.iid);
		});
});
body{
  padding: 20px;
}

a {
    color: #3e6d8e !important;
    background-color: #E1ECF4;
    padding: 2px 5px;
}
.tag_info{
  position: reletive;
  width: 130px;
  height: 30px;
  display:none;
  background-color: black;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>tag1</a>
<a>tag2</a>

As you see, it will be repeated every time. How can I execute it once per hover? And why the position doesn't apply?

Also is what I'm doing a right algorithm for such thing?

Thank you.

Upvotes: 2

Views: 80

Answers (2)

S Jung
S Jung

Reputation: 160

Like Dij said:

  • What you're doing:
    • setInterval - (repeats your function every 525ms)
  • What you want:
    • setTimeout - (executes your function once after 525ms delay)

Read more:

setInterval https://www.w3schools.com/jsref/met_win_setinterval.asp

setTimeout https://www.w3schools.com/jsref/met_win_settimeout.asp

Upvotes: 1

Dij
Dij

Reputation: 9808

I am not sure why you are using setInterval but I think this should work. I removed setInterval and everytime the mouseenter event occurs we can append <div class='tag_info'> and every time mouseleave event occurs we can remove the the appended div.

$(document).ready(function(){
    $('#test').bind('mouseenter', function() {
      var self = $(this);
      	 var tag_name = self.text(),
             top      = self.position().top + self.outerHeight(true),
             left     = self.position().left;
         self.append("<div class='tag_info'>Some explanations about"+tag_name+"</div>")
         $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);   
		}).bind('mouseleave', function(){
    	$(this).children('.tag_info').remove();
		});
});
body{
  padding: 20px;
}

a {
    color: #3e6d8e !important;
    background-color: #E1ECF4;
    padding: 2px 5px;
}
.tag_info{
  position: reletive;
  width: 130px;
  height: 30px;
  display:none;
  background-color: black;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="test">tag1</a>

Upvotes: 1

Related Questions