STFLightning
STFLightning

Reputation: 83

Change Image On Hover Javascript

I have done my research and looked at tons of things, but none of them are working for me. This is my code at the moment. The original image displays fine, but nothing happens when I hover.

Javascript (In <head>)

<script>
    function onHover()
    {
        $("#news").attr('src', 'img/newsHover.png');
    }

    function offHover()
    {
        $("#news").attr('src', 'img/news.png');
    }
</script>

HTML

<img id="news" onmouseover="onHover();" onmouseout="offHover();" height="100px" width="100px" src="img/news.png"></a>

Upvotes: 1

Views: 14237

Answers (4)

Ivošš
Ivošš

Reputation: 1156

So you can use only this example:

<img 
    src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/clean.png' 
    onmouseover="this.src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/exit.png'"
    onmouseout="this.src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/clean.png'"
    height="100px"
    width="100px"
    id="news"
>

EXAMPLE

Upvotes: 0

abhiklpm
abhiklpm

Reputation: 1653

A pure java script answer, no need of any external functions or jquery

<img id="news" onmouseover="this.src='img/newsHover.png'" onmouseout="this.src='img/news.png'" height="100px" width="100px" src="img/news.png"> 

Upvotes: 6

Ivošš
Ivošš

Reputation: 1156

this is very easy example, not animation:

HTML:

<img src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/clean.png'>

use jQuery:

$(document).ready(function(){
    $('img').hover(
        function(){$(this).attr("src","https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/exit.png")},
        function(){$(this).attr("src","https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/clean.png")}
    );
});

Example Not Animation


And this is example with animation:

HTML:

<img src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/clean.png' class='clean' >
<img src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/exit.png' class='exit' >

CSS:

img{
    position:absolute;
    top:0;
    left:0;
}

use jQuery:

$(document).ready(function(){

    $(".exit").hide();

    $(".clean").hover(function(){
        $(".clean").fadeOut();
        $(".exit").fadeIn();
    });    

    $(".clean").mouseleave(function(){
        $(".exit").fadeOut();
        $(".clean").fadeIn();
    });    

});

Example With Animation

Upvotes: 0

Dan
Dan

Reputation: 7744

There may be a good reason for what you're doing, but are you sure you need to use JavaScript?

If you're not doing anything fancy then it would probably be better to use the CSS hover selector: http://www.w3schools.com/cssref/sel_hover.asp

Upvotes: 0

Related Questions