I am using an image for an input (button) within a form on my website, and would like to swap the image on hover.
The following code works fine in a stand alone demo. The images swap nicely.
However… when I integrate this code into the rest of the form code, it fails.
I am guessing it is because the script calls for getElementsByTagName('input')
with the tag name being input
.
Therefore… perhaps because the form contains other ‘inputs’, the function targets the other inputs as well, and simply dies??????
Is there a way to execute this same function, and target the specific input without using the getElementsByTagName('input')
, or by tweaking it some way?
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');
};
}
<input type="image" src="/images/image1.png" data-alt-image="/images/image2.png" />
3
Answers
If you use
querySelectorAll
, then you can use CSS selectors – this way, you can narrow down your list however you like (limit is CSS selectors only).In the snippet below I broke up your code a bit, but the main point (regarding your question) is that with
querySelectorAll
I could narrow down theinput
list with atype
. This way, if really a clash is the problem in your context, the problem should be solved (of course, you could be adding aclass
, or just "filter" for thedata-alt-image
).Also, by updating the iterator function (
for...i++
->inputs.forEach
), it works nicely with multiple inputs.You specified JavaScript and jQuery, so here is a short & sweet jQuery solution:
Explanation:
src
anddata-alt
attributes.hover()
function has two callbacks, one for entering, one for leavingswapImage()
function, which swaps the values of thesrc
and adata-alt
attributesThis is fairly simple if you use data attributes; set up the original with
swapper.dataset.origImage = swapper.getAttribute('src');
(or put that in the HTML originally as data attributes) then just swap them on the mouse events