Set variable with the ID of last hovered DIV / SPAN

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts:107

Set variable with the ID of last hovered DIV / SPAN

Hi,
How can I set a variable with the id of the last hovered DIV or SPAN in page, using JavaScript /jQuery?
I tryed with "onmouseover" event, but I cannot set this event on each div /span. Besides, there are also div /span elements without an id.
Thanks.

Admin Posts:805
Hi,
Try this code.
- Simple JavaScript:

Code: Select all

<div id="content">
  <span>https://coursesweb.net/</span>
  <div id="id1">http://www.marplo.net/</div>
  <span id="id2">http://php.net/</span>
  <div id="id3">http://jquery.com/</div>
</div>
<script>
var id_hover = '';    // will store the id of the last hovered DIV or SPAN (if has any)
var div_span = document.querySelectorAll('div, span');
for(var i=0; i<div_span.length; i++) {
  div_span[i].addEventListener('mouseenter', function(){
    if(this.id != '' && this.id != undefined) id_hover = this.id;
  //  console.log(id_hover);    // debug
  }, false);
}
</script>
- With jQuery:

Code: Select all

HTML CODE ...
<script>
var id_hover = '';    // will store the id of the last hovered DIV or SPAN (if has any)
$(document).on({
  mouseenter: function(evt) {
    var thisid = $(evt.target).attr('id');
    if(thisid != '' && thisid != undefined) id_hover = thisid;
 // console.log(id_hover);    // debug
  }
}, 'div, span');
</script>