3

How could I have two pictures,one for show while I am onmouseover and one for hide while I am onmouseout?

<td id="img" onmouseover="showIt(this.src)" onmouseout="hideIt()" src="image1.jpg " src="default.jpg">my box" </td>
    
    
    function showIt(imgsrc)
    {
    document.getElementById('img').src=imgsrc;
    }
    
    function hideIt()
    {
    document.getElementById('img').src="default.png";
    }
  • `td id="img"`? Should it not be ` – Rajesh Nov 30 '20 at 03:33
  • While I have my mouse on this td I want to show one image inside this td, When I do mouseout another image will be shown –  Nov 30 '20 at 03:35
  • The only argument passed to an EventListener is the EventObject. I would separate your HTML and JavaScript completely. It will save you a world of headaches down the road. – StackSlave Nov 30 '20 at 03:36
  • @klopepen So, to simplify, you will always have an image in `td`. Based on mouse position, it'll change. So it does not have anything to do with `td`. Add an image tag and use it – Rajesh Nov 30 '20 at 03:41

4 Answers4

1

You can achieve this using just CSS as well. Note, CSS is always faster than JS in terms of DOM manipulation.

Also as commented, you will have to use img tag instead

CSS Approach

.hover-toggle {
  content: url('https://reputationtoday.in/wp-content/uploads/2019/11/110-1102775_download-empty-profile-hd-png-download.jpg');
  width: 100px;
  height: 100px;
  border: 1px solid gray;
}

.hover-toggle:hover {
  content: url('https://img.favpng.com/0/8/3/user-profile-computer-icons-internet-bot-png-favpng-92SBLLR7CwZpN8Vm6MUsuU4Sd.jpg')
}
<img class='hover-toggle'>

As rightly commented by @StackSlave, hover will have issues on mobile device.

:hover is a problem on mobile. I would use Element.onmouseenter and Element.ontouchstart and Element.onmouseleave and Element.ontouchend instead.

JS Approach

function registerEvents() {
  const img = document.getElementById('img');
  img.addEventListener('mouseenter', showIt)
  img.addEventListener('mouseleave', hideIt)
}

function showIt() {
  this.src = 'https://img.favpng.com/0/8/3/user-profile-computer-icons-internet-bot-png-favpng-92SBLLR7CwZpN8Vm6MUsuU4Sd.jpg';
}

function hideIt() {
  this.src = 'https://reputationtoday.in/wp-content/uploads/2019/11/110-1102775_download-empty-profile-hd-png-download.jpg';
}

function initialize() {
  const img = document.getElementById('img');
  // set default state
  hideIt.call(img)
  
  // Register events
  registerEvents()
}

initialize()
#img {
  width: 100px;
  height: 100px;
  border: 1px solid gray;
}
<img id='img'>

Reference:

Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

use <img> tag instead of <td>

 <img src="ss" onmouseover="add(event)" onmouseout="remove(event)">

Java Script

function add(e){
          e.target.setAttribute("src", "https://shiharadil.netlify.app/static/media/me.9688d9df.jpg");
}
      
      function remove(e){
          e.target.setAttribute("src", "ss");
}
Shihara Dilshan
  • 193
  • 2
  • 14
0

maybe you want to track the original src like this.

<img id="myimg" src="https://images.freeimages.com/images/small-previews/867/volcanic-mt-ngauruhoe-1378772.jpg" onmouseover="mouseover()" onmouseout="mouseout()" />
function mouseover() {
  const elm = event.target;
  elm.setAttribute("orig_src", elm.src);
  elm.src = "https://images.freeimages.com/images/small-previews/647/snowy-mountain-1378865.jpg";
}

function mouseout() {
  const elm = event.target;
  elm.src = elm.getAttribute("orig_src");
}

https://jsfiddle.net/71zfw8s4/

D. Seah
  • 4,472
  • 1
  • 12
  • 20
0

I would separate your HTML, CSS, and JavaScript, so everything but the HTML is cached. It also makes it easier to reuse code. Here's an in-depth example, of how I might do what you're asking:

//<![CDATA[
/* js/external.js */
let get, post, doc, htm, bod, nav, M, I, mobile, beacon, S, Q, hC, aC, rC, tC, inArray, shuffle, isNum, isInt, rand; // for reuse on other loads
addEventListener('load', ()=>{
get = (url, func, responseType = 'json', context = null)=>{
  const x = new XMLHttpRequest;
  const c = context || x;
  x.open('GET', url); x.responseType = responseType;
  x.onload = ()=>{
    if(func)func.call(c, x.response);
  }
  x.onerror = e=>{
    if(func)func.call(c, {xhrErrorEvent:e});
  }
  x.send();
  return x;
}
post = (url, send, func, responseType ='json', context = null)=>{
  const x = new XMLHttpRequest;
  if(typeof send === 'object' && send && !(send instanceof Array)){
    const c = context || x;
    x.open('POST', url); x.responseType = responseType;
    x.onload = ()=>{
      if(func)func.call(c, x.response);
    }
    x.onerror = e=>{
      if(func)func.call(c, {xhrErrorEvent:e});
    }
    let d;
    if(send instanceof FormData){
      d = send;
    }
    else{
      let s;
      d = new FormData;
      for(let k in send){
        s = send[k];
        if(typeof s === 'object' && s)s = JSON.stringify(s);
        d.append(k, s);
      }
    }
    x.send(d);
  }
  else{
    throw new Error('send argument must be an Object');
  }
  return x;
}
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
beacon = (url, send)=>{
  let r = false;
  if(typeof send === 'object' && send && !(send instanceof Array)){
    let d;
    if(send instanceof FormData){
      d = send;
    }
    else{
      let s;
      d = new FormData;
      for(let k in send){
        s = send[k];
        if(typeof s === 'object' && s)s = JSON.stringify(s);
        d.append(k, s);
      }
    }
    r = nav.sendBeacon(url, d);
  }
  else{
    throw new Error('send argument must be an Object');
  }
  return r;
}
S = (selector, within)=>{
  var w = within || doc;
  return w.querySelector(selector);
}
Q = (selector, within)=>{
  var w = within || doc;
  return w.querySelectorAll(selector);
}
hC = (node, className)=>{
  return node.classList.contains(className);
}
aC = function(){
  const a = [...arguments];
  a.shift().classList.add(...a);
  return aC;
}
rC = function(){
  const a = [...arguments];
  a.shift().classList.remove(...a);
  return rC;
}
tC = function(){
  const a = [...arguments];
  a.shift().classList.toggle(...a);
  return tC;
}
inArray = (mixed, array)=>{
  if(array.indexOf(mixed) === -1){
    return false;
  }
  return true;
}
shuffle = array=>{
  let a = array.slice(), i = a.length, n, h;
  while(i){
    n = Math.floor(Math.random()*i--); h = a[i]; a[i] = a[n]; a[n] = h;
  }
  return a;
}
isNum = mixed=>typeof mixed === 'number' && !isNaN(mixed); isInt = mixed=>Number.isInteger(mixed);
rand = (min, max)=>{
  let mn = min, mx = max;
  if(mx === undefined){
    mx = mn; mn = 0;
  }
  return mn+Math.floor(Math.random()*(mx-mn+1));
}
// magic under here - can put on load on another page except end load
const test = I('test'), one = I('one'), two = I('two');
const presto = ()=>{
  tC(one, 'out'); tC(two, 'out');
}
if(mobile){
  test.ontouchstart = test.ontouchend = presto;
}
else{
  test.onmouseenter = test.onmouseleave = presto;
}
}); // end load
//]]>
/* css/external.css */
*{
  box-sizing:border-box; font-size:0; color:#000; padding:0; margin:0; overflow:hidden;
}
html,body,.main{
  width:100%; height:100%;
}
.main{
  background:#333; overflow-y:auto;
}
#test{
  position:relative;
}
#test,#test>img{
  width:64px; height:64px;
}
#test>img{
  position:absolute; top:0; left:0; transition:opacity 0.5s ease-in-out; cursor:pointer;
}
#test>img.out{
  opacity:0;
}
  
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
    <title>Title Here</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />
    <script src='js/external.js'></script>
  </head>
<body>
  <div class='main'>
    <div id='test'>
      <img id='one' src='https://lh4.googleusercontent.com/-dQCbHQsqFnA/AAAAAAAAAAI/AAAAAAAAAAA/AMZuuclQUPeKb5dc9mdspXEBq7nIrM67RA/s96-c/photo.jpg?sz=64' />
      <img class='out' id='two' src='https://i.stack.imgur.com/DvKY9.png?s=64&g=1' />
    </div>
  </div>
</body>
</html>

Look at // magic under here and you'll see the code you can use will be minimal with the above Library I created. Use freely.

StackSlave
  • 10,613
  • 2
  • 18
  • 35