简体   繁体   中英

Change the image of a JSF commandbutton with DHTML event onmouseover

I want to change the image of my button when the mouse goes over it.

I rode the DHTML event onmouseover, can do that for me, but how?

Do i need to create a javascript also for it?

What should i do to make it work?

This is my current code:

<h:commandButton class="btn" image="/resources/images/mainbtn1.png" onmouseover="/resources/images/mainbtn2.png"/">

The <h:commandButton image="foo.png"> generates a HTML <input type="image" src="foo.png"> . The onmouseover attribute (like as all on* attributes) should point to JavaScript functions. However, you're putting the image path plain there. This would only result in a JavaScript error (which you would have noticed if you were using Firebug or WDT).

You need to write some JS which changes the src attribute of the image button accordingly:

onmouseover="this.src='/resources/images/mainbtn2.png'"

Don't forget to add an onmouseout which changes the image back.


Unrelated to the concrete problem, the normal practice is to use CSS background images for this. The HTML <input type="image"> has technically an entirely different purpose. It represents namely an image map which allows you to send the mouse coordinates of where you have clicked in the image map. You're apparently not interested in this information as you're not using a static image.

Eg

<h:commandButton value="" styleClass="mybutton" />

which generates

<input type="submit" value="" class="mybutton" />

and add this CSS (kickoff example)

.mybutton {
    margin: 2px;
    padding: 0;
    border: 0;
    width: 100px;
    height: 20px;
    background-image: url('foo.png');
    cursor: pointer;
    overflow: visible;
}

.mybutton:hover {
    background-image: url('bar.png');
}

This is not only better reuseable/maintainable, but also doesn't require JS support.

Yes, all onXXX attributes are for JavaScript event handlers. You need to have a JavaScript function written for that. Something like this:

function changeImage() {
    this.style.backgroundImage = "url('path/to/image.png')";
}

And invoked using:

<h:commandButton class="btn" image="/resources/images/mainbtn1.png" onmouseover="changeImage()" />

Note: I can't provide you the exact JavaScript as it entirely depends on how the markup is generated by the JSF library that you're using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM