Is it possible to switch the button's image when hovering over it?

Hey there! I have an HTML button configured like this:

<input type="image" src="derp.png">

Since the image is not assigned via CSS, how can I change it on hover?

Answer №1

An easy and straightforward solution:

<input type="image" src="derp.png" onMouseOver="this.src='aderp.png'" onMouseOut="this.src='derp.png'">

See it in action on JSFiddle: http://jsfiddle.net/F8yJs/

While there are more elegant methods to achieve this effect, this one will get the job done.

Answer №2

Here is a potential solution that may work (although not tested yet). It involves storing the alternate image in a custom data-* attribute so the script knows where to retrieve it from, and then saving the original src in another custom data-* attribute to restore it on mouseout:

var inputs = document.getElementsByTagName('input');

for (var i = 0, len = inputs.length; i < len; i++) {
    input = inputs[i];
    input.onmouseover = function(){
        this.setAttribute('data-orig-image',this.getAttribute('src'));
        this.src = this.getAttribute('data-alt-image');
    };
    input.onmouseout = function(){
        this.src = this.getAttribute('data-orig-image');
    };
}​

Check out the JS Fiddle demo here.

Please note that the above method requires your input element to have the following structure in HTML:

<input type="image" src="http://path.to/default/image.png" data-alt-image="http://path.to/mouseover/image.png" />​

An additional CSS option has been added, although it is not perfect and works best when the input does not initially have an image set in its src attribute:

input[type=image] {
    background-image: url(http://davidrhysthomas.co.uk/img/dexter.png);
    background-repeat: no-repeat;
    background-position: 50% 50%;
    width: 200px;
    height: 185px;
}
input[type=image]:hover,
input[type=image]:active,
input[type=image]:focus {
    background-image: url(http://davidrhysthomas.co.uk/img/mandark.png);
}​

View the updated JS Fiddle demo here.

Answer №3

You have a couple of choices available:

1) Utilize CSS

input.change {
background-image:url(derp.png);
}

input.change:hover {
background-image:url(mouseover.png);
} 

(Simply add the 'change' class to the input element in your code snippet.)

2) Implement JavaScript

<input type="image" src="derp.png" onmouseover="this.src='mouseover.png'" onmouseout="this.src='derp.png'">

Answer №4

Most solutions provided were centered around JavaScript and CSS, however, I recommend using a jQuery approach for this problem. By utilizing the hover() function in jQuery, you can easily achieve the desired effect.

Here is a sample jQuery script:

$(document).ready(function() {
 $('#img1').hover(function() {
    $('#img1').attr('src','second_img.jpg');
  }, function() {
   // You can add additional code here
   alert('Mouse hovered out');
 });
});

HTML snippet:

<input id="img1" type="image" src="first_img.png">

To see a live demonstration of this solution in action, check out this working example.

Answer №5

One creative approach could involve placing an image beneath the button and adjusting the alpha channel of the button's background image to 0, allowing the image underneath to shine through.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Swap a jQuery class with another if the class for ul li is currently active

I am currently developing a form builder and I would like to customize the appearance, specifically changing the color of the text. I want the text to be white when the class is set to active, and black when the class is not active. Is there a way to achi ...

Creating a CSS background that adjusts to fit any screen resolution

Hey there, I'm a beginner to all of this. I want my background image to adjust to fit any web browser resolution, regardless of the size. So far, I've come across this nifty little trick: html { background: url(images/bg.jpg) no-repeat center ...

Issue with Scrollspy Functionality in Bootstrap 4

Scrollspy feature isn't working in my code. <nav class="navbar navbar-expand-lg fixed-top navbar-dark" role="navigation"> <div class="container"> <a class="navbar-brand" href="#featured"><h1></h1></a> < ...

Controlling Formatting in ASP.NET

Feeling puzzled by a seemingly simple question with no clear solution in sight. We're attempting to transition an interface to an ASP.NET control that currently appears like this: <link rel=""stylesheet"" type=""text/css"" href=""/Layout/CaptchaLa ...

What is the best way to adjust the spacing between grid items in Material UI?

Is there a way to automatically adjust the spacing between content boxes without disrupting the layout? I've tried using spacing, padding, and margin properties, but they end up messing up my design. Is there a solution that mimics the column-gap and ...

Tips for ensuring the position of buttons remains consistent no matter the size of the image

I am facing an issue with maintaining the button location when an image is added. My goal is to ensure that the button's position remains horizontal consistently. Front-end: React CSS framework: semantic-ui-react render() { return ( &l ...

Place icon on the left side of the header one

Is there a way to adjust the icon so that it fits correctly next to my heading? <div style="width:100%;"> <div style="float: left;width:7%;min-width:40px;"> <img src="http://superfood-zentrum.info/wp-content/uploads/2016/03/square.png ...

Rotation using CSS in Internet Explorer 8

Can anyone help me with a CSS solution for rotating elements in IE8? I've tried some solutions that claim to work in IE8, but they're not working for me. What am I doing wrong? Here's what I've attempted: <!DOCTYPE html> <htm ...

Send the chosen value from a dropdown menu to a PHP script

<style type="text/css"> form select { display:none; } form select.active { display:block; } </style> <script type="text/javascript"> window.onload = function () { var allElem = document. ...

Is there a way to extend this section to fill the entire screen height without any white space at the bottom?

We've been working on extending the content to the full height of the screen, but no matter what we try, there's always some white space lingering at the bottom. Any suggestions on how to fix this issue? section { height: 100vh; background ...

Difficulty maintaining hover state on menu while navigating to submenu on an HTML page

I successfully implemented a side menu that displays the submenu when hovering over menu items. However, I am encountering two issues: 1. When I hover over a menu item and the submenu appears, the hover state of the menu item disappears. I would like the m ...

The functionality of reordering columns, virtual scrolling, and resizing the grid in jqgrid are not functioning properly

Implementing jqgrid with Symfony to display a datagrid has been a challenging task for me. Thanks to Oleg's insightful response, many of the major issues have been resolved. Below is a snippet of my code: <link rel="stylesheet" type="text/css" ...

Tips for showcasing dynamic information from a database with three columns utilizing Bootstrap 4

In my code below, I am trying to display details with 3 columns per row using the Bootstrap row class. I have attempted to make some changes to the div and add a condition, but I'm facing some issues. <div class="container"> <?php ...

Customizing the Height of Elements in Bootstrap

When working with two columns in bootstrap, let's say one column has a height of 800 PX. If you want the text in the second column to start after 200 PX, is there a way to achieve this without using padding or margin? Are there any predefined classes ...

Ensure that the table tag in testWeb(jspackage.JSAssignmentDiscount) contains exactly 3 rows and assess whether it complies with the CSS criteria for tables and table rows

Criteria: The table must include the product name, product price, and season information. The product name and product price should be input text boxes labeled with name and price respectively. The season selection should be a dropdown menu labeled with s ...

Include a scrollbar within a Bootstrap table grid under a div with a width of 12 columns

How can I add a scrollbar to the grid below? It is using a bootstrap table inside a bootstrap col 12 div. I have attempted to use the following CSS, but it does not apply a scrollbar, it only disrupts the columns. divgrid.horizontal { width: 100%; ...

"Using CSS to align content in a table-row format on an HTML display

I'm struggling to align two components using the <div display='table-cell'> method. The first component is showing a gap at the top which I want to remove in order to have them aligned perfectly. Check out the JsFiddle example here: h ...

Displaying every nth image in a new row of a CSS grid

I have a react component and I want to arrange 3 photos inline in a row with their names below each photo, and then continue in new rows for the next set of 3 elements and so on... I attempted to use :nth-child(3n+1) but encountered some issues... const P ...

Issue with displaying content in AngularJS view set by a service

I'm currently facing a challenge in accessing the view with an expression that doesn't seem to be working correctly. Here is my Service: angular.module('myApp', []).service('myService', function($timeout){ this.sayHello = ...

Is it possible to include a border/stroke on a Raphael picture?

Currently, I am attempting to enhance a Raphael image element by adding either a border, stroke, or drop shadow. My end goal is to create an animated glowing border effect. Previously, I successfully implemented this on traditional HTML elements using Java ...