Skip to content Skip to sidebar Skip to footer

How To Change Content Of Div On Hover Using Jquery/javascript

I'm trying to change the contents of a div when it's hovered over using JQuery. I've seen answers on stack overflow, but I can't seem to get it working. I've tried $( 'imgDiv' ).

Solution 1:

You can use jQuery's .hover() function along with the .text() function to do what you want. Also, no need for document.getElementById:

$("#imgDiv").hover(
  function() {
    $("#titleDiv").text("hovering");
  },
  function() {
    $("#titleDiv").text('title');
  }
);
body {
  background: white;
  padding: 20px;
  font-family: Helvetica;
}

#imgDiv {
  width: 100px;
  height: 100px;
  background-color: pink;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divid="imgDiv"><divid="titleDiv">title</div></div>

Solution 2:

You can target the div with jQuery, and store it's original value. On mouseout, you can restore it. Also using mouseenter reduces the number of times the logic processes as mouseover will fire for every mouse move over the element.

var $titleDiv = $('#titleDiv');

$("#imgDiv")
  .on('mouseenter', function() {
    $titleDiv.data('originalText', $titleDiv.text());
    $titleDiv.text('hovering');
  })
  .on('mouseout', function() {
    $titleDiv.text($titleDiv.data('originalText'));
  });
body {
  background: white;
  padding: 20px;
  font-family: Helvetica;
}

#imgDiv {
  width: 100px;
  height: 100px;
  background-color: pink;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divid="imgDiv"><divid="titleDiv">title</div></div>

Solution 3:

First of all, replace $("imgDiv") with $("#imgDiv") to get the element with id (#) imgDiv.

Then $("tdiv") doesn't exist, you probably mean $("div") to select a <div>tag in your DOM.

And finally, $("tdiv").textContent doesn't exist. You can try $("div").html() or $("div").text() to get the <div> tag content

--

Quick reminder : jQuery documentation on selectors

$("div") will select the <div> tags

$(".element") will select tags with class="element"

$("#element") will select tags with id="element"

Solution 4:

You need to try like this

$( "#imgDiv" ).mouseover(function() {
			      $("#titleDiv").text("hovering");
			  }).mouseleave( function() {
			    $("#titleDiv").text('title');
			  });
body {
  background: white;
  padding: 20px;
  font-family: Helvetica;
}
#imgDiv {
  width: 100px;
  height: 100px;
  background-color: pink;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divid="imgDiv"><divid=titleDiv>title</div></div>

Solution 5:

Easy solution,

var s = document.getElementsByTagName('div');
functionout() {
 s[0].innerHTML = 'hello';
}

functionibn() {
 s[0].innerHTML = 'Myname';
}
<divonmouseout = 'out()'onmouseenter = 'ibn()'> Myname </div>

Post a Comment for "How To Change Content Of Div On Hover Using Jquery/javascript"