2

I have 4 image button containing a image. on mouse over i have to change the image(i.e load a new image on the button). Here is the code.

<div class ="submit" id="submit" >
    <input  type="image" src="dump.png" value="Dumb" class ="Dumb" id="Dumb" onclick="posting_by_user('Dumb')" />
    <input  type="image" src="informative.png" value="Informative" class ="Informative" id="Informative" onclick="posting_by_user('Informative')"/>
    <input  type="image" src="brilliant.png" value="Brilliant" class ="Brilliant" id="Brilliant" onclick="posting_by_user('Brilliant')"/>
    <input  type="image" src="cool.png" value="Cool" class ="Cool" id="Cool" onclick="posting_by_user('Cool')"/>
</div>

Here I have loaded dump.png, informative.png, brilliant.png and cool.png. on mouse over on each button i have to change the image.

Mikael Östberg
  • 16,982
  • 6
  • 61
  • 79
Raju.allen
  • 341
  • 2
  • 9
  • 21

4 Answers4

3

Try this

$(document).ready(function() {
$('input[type=img]')
    .mouseover(function() { 
        var src =  "mouseover.png";
        $(this).attr("src", src);
    });
Hemesh Singh
  • 1,105
  • 2
  • 9
  • 13
2
<input  type="image" src="dump.png" value="Dumb" class ="Dumb" id="Dumb" onclick="posting_by_user('Dumb')" onmouseover="changeImg.call(this)" />

function changeImg(){
this.setAttribute("src","newImageFileName.jpg");
}

Segregating your code from html is always advised.. this answer will be helpful as it is cleaner and good for debugging..

Vivek Chandra
  • 4,240
  • 9
  • 33
  • 38
  • @raju.allen if you are new to stackoverflow,there is a tick mark next to each answer,you can accept an answer by clicking on that tick mark.. accept the answer which best suits/fixes your problem.. – Vivek Chandra Feb 07 '12 at 06:49
2
<input  type="image" src="dump.png" value="Dumb" class ="Dumb" id="Dumb" 
onclick="posting_by_user('Dumb')" 
onmouseover="this.src='informative.png';" 
onmouseout="this.src='dump.png';" />
amka
  • 111
  • 3
1

You can use either Javascript or CSS for this, below is the javascript approach.

window.addEventListener("load", function load (event) {
    window.removeEventListener("load", load, false);
    tieEvents();
}, false);

function tieEvents() {
    var button = document.getElementById('Dumb');

    button.addEventListener("mouseover", hovered, false);
    button.addEventListener("mouseout", unhovered, false);

    function hovered() {
        button.src = "anotherimg.png";
    }

    function unhovered() {
        button.src = "anotherimg.png";
    }
};

JSFiddle Demo

Note that setting events in HTML is not a good practice, it's better to tie them up in Javascript.


The CSS way is as follows:

#Dumb {
    backgroud: url("dump.png");
}

#Dumb:hover {
    backgroud: url("another.png");
}

JS Fiddle Demo

fardjad
  • 20,031
  • 6
  • 53
  • 68