I am using buttons on which I have given images. I want to change the image on mouseover using javascript. My code is working on Chrome but its not working for firefox. Please help.
Here is the code
Javascript
function rolloverInit() {
for (var i=0; i<document.images.length; i++) {
if (document.images[i].parentNode.tagName == "BUTTON") {
setupRollover(document.images[i]);
}
}
}
function setupRollover(thisImage) {
thisImage.outImage = new Image();
thisImage.outImage.src = thisImage.src;
thisImage.onmouseout = rollOut;
thisImage.overImage = new Image();
thisImage.overImage.src = "images/" + thisImage.alt + "1.png";
thisImage.onmouseover = rollOver;
thisImage.parentNode.childImg = thisImage;
thisImage.parentNode.onblur = rollOutChild;
thisImage.parentNode.onfocus = rollOverChild;
}
function rollOut() {
this.src = this.outImage.src;
}
function rollOver() {
if(prevFlag == 0 && this.id==previous1)
{
return;
}
if(nextFlag == 0 && this.id==next1)
return;
this.src = this.overImage.src;
}
HTML
<button id="prevLinkSimplyP" class="previous"><img src="images/previous.png" height="50" width="50" id="previousSimplyP" alt="previous"/></button>
<button id="startAgainSimplyP" class="reload"><img src="images/reload.png" height="50" width="50" id="reloadSimplyP" alt="reload" /></button>
<button id="nextLinkSimplyP" class="next" ><img src="images/next.png" height="50" width="50" id="nextSimplyP" alt="next"/></button>
At the risk of being accused of not answering your question properly, why don't you use JQuery to solve this problem? You can not only reduce the code to just a few lines, but it will work in all browsers:
http://api.jquery.com/mouseover/
There are examples here of a mouseover/mouseout working exactly as you describe. My suggestion is to learn JQuery as it will save you a lot of time beating your head against the trials of working with raw JavaScript.
I also want to point out that alt attributes typically hold text to be displayed in the event that your images don't load or a user agent is loading your page that doesn't render images. I also understand that it has SEO benefits when text on images cannot be scanned by the Google Bot.
As for your question, I don't see the following functions, rollOutChild and rollOverChild, defined:
thisImage.parentNode.onblur = rollOutChild;
thisImage.parentNode.onfocus = rollOverChild;
Try this
if (document.images[i].parentNode.tagName.toLowerCase() == "button") {
setupRollover(document.images[i]);
}
I think your problem could be related to Firefox trying to match your tag's name uppercase only.
Use jQuery, it is compatible with all types of browsers.
Related
I'm trying to enable onMouseOver and onMouseOut for all of my icons and replacing them with unique icons.
Originally I had this:
<img id="EEProfile" src="images/EEProfile.png" alt="Employee Profile" onMouseOver="mouseOver()" onMouseOut="mouseOut()">
External JS file:
function mouseOver() { document.getElementById("EEProfile").src = 'images/EEProfile_Hover.png'; }
function mouseOut() { document.getElementById("EEProfile").src = 'images/EEProfile.png'; }
There are a few issues with this:
This method works on IE but for some reason on Chrome onMouseOut isn't working, so hover images are remaining.
Requires some inline javascript. I'm trying to move towards eliminating all inline JS.
Requires me to hardcode image paths for each and every image on the page.
Since all image paths are the same and follow the same naming convention, which is just
'images/ImageID.png' or 'images/ImageID_Hover.png'
I was hoping to implement something like this:
Pseudocode HTML:
<img id="EEProfile" src="images/EEProfile.png" alt="Employee Profile" onMouseOver="mouseOver(this.id)" OnMouseOut="mouseOut(this.id)">
Pseudocode JavaScript:
function mouseOver(id) { document.getElementById("id").src = 'images/id.png'; }
function mouseOut(id) { document.getElementById("id").src = 'images/id_Hover.png'; }
I want to pass over the ID of the image element to the mouseOver and mouseOut functions as a parameter, then use that ID's string literal in the image path so I don't have to hardcode every image's path. Is something like this possible? Is there a way to do this without inline JS?
I've considered using content:hover without JS but it isn't supported in IE.
I would give all the images you want to have the hover effect a specific class name. Then you can get all the element with that class and add event listeners for mouseover and mouseout. I used the current src to determine the new src. You could just as easily get the id with event.target.id and use that to build the src. You also could build the regular expression to match more than just .png files.
(function(window, document, undefined)
{
var images = document.getElementsByClassName('hoverImage');
for (var i = 0; i < images.length; i++) {
images[i].addEventListener('mouseover', imageMouseOver, false);
images[i].addEventListener('mouseout', imageMouseOut, false);
}
})(window, window.document);
function imageMouseOver(event)
{
event = event || window.event;
var image = event.target;
image.src = getNewImagePath(image.src);
console.log(image);
}
function imageMouseOut(event)
{
event = event || window.event;
var image = event.target;
image.src = getNewImagePath(image.src);
console.log(image);
}
function getNewImagePath(path)
{
var newPath;
if (path.indexOf('_Hover') === -1) {
newPath = path.replace('.png', '_Hover.png');
} else {
newPath = path.replace('_Hover', '');
}
return newPath;
}
.hoverImage {
width: 50px;
height: 50px;
}
<img id="1" src="images/1.png" alt="Employee Profile" class="hoverImage">
<img id="2" src="images/2.png" alt="Employee Profile" class="hoverImage">
<img id="3" src="images/3.png" alt="Employee Profile" class="hoverImage">
I have a div that contains a number of Instagram images, produced by the instafeed.js plugin. After running the plugin, the resultant HTML looks like this:
<div id="instafeed">
<a><img /></a>
<a><img /></a>
<a><img /></a>
etc...
</div>
I am trying to find a way to load the contents of this div into an array; I believe that the easiest way would be to just take the tags, which is fine.
I'm pretty inexperienced with both JS and jQuery, which is why I'm having difficulty achieving this and I've not been able to find any forum posts that quite do what I'm hoping to achieve.
So far, all I'm trying to do is load the contents of the div into an array and print it back out to the document, which should (in my mind anyway) add the tags back into the HTML. I'm trying with both JavaScript and jQuery and having little success with either. I'd appreciate any thoughts:
JS:
var containerDiv = document.getElementById('instafeed');
var pics = containerDiv.getElementsByTagName('img');
console.log(pics); //Tells me at least that I have an array of img
for (var i = 0; i < pics.length; i++) {
document.write(pics[i]);
} //Seemingly does nothing
jQuery:
(I'm really sorry if this code is just all wrong, I really don't know jQuery very well at all)
$(document).ready(function() {
var pics = [];
$('#instafeed').find('img').each(function() {
pics.push($(this));
});
for (i = 0; i < pics.length; i++) {
console.log(pics[i]);
}
});
Any thoughts, tips or pointers would be much appreciated.
Edit:
Just to add a little background to my problem, to avoid causing any more confusion.
I'm trying to pull four random images from a user-specific Instagram feed for display on a website. instafeed.js can pull just four images and it can randomise the images, but Instagram itself always sends the four most recent images, so the plugin is just randomising the order of the same four pictures each time.
I'm trying to let the plugin send through every picture, which will go into the div instafeed. From here I want to load all of the contained images into an array so that I can randomly pick four images for display on the site.
JQuery code that you write is correct. Only you need the div where you need to put the images.
$(document).ready(function() {
var pics = [];
$('#instafeed').find('img').each(function() {
pics.push($(this));
});
for (i = 0; i < pics.length; i++) {
$('div#yourDiv').append(pics[i]);
}
});
See the line of the for()
You can extract only the SRC of the images and then make like you want
$('#instafeed').find('img').each(function() {
pics.push($(this).attr('src'));
});
console.log(pics); // returns an array of src.
Thank you to everyone who has tried to help me along with this. It turns out that the problem I was having stemmed from my query attempting to run before instafeed.js had been able to pull the images through from Instagram, and so there was nothing for it to find in the div. I've managed to fix this with a setTimeout.
For anyone who is interested, and just in case anyone else might come across this in future with a similar problem, here is my complete code (it's a little inelegant I'm sure, but I'm still a relative novice at JS.)
function snagImages() {
var pics = [];
$('div#instafeed').find('img').each(function() {
pics.push($(this).attr('src'));
});
reduceGallery(4, pics);
}
function reduceGallery(limit, pics) {
if (limit === undefined) {
limit = 4;
}
var gallery = [];
while (gallery.length < limit) {
var j = Math.floor(Math.random() * pics.length);
if ( gallery.indexOf(pics[j]) > -1) {
continue;
}
gallery.push(pics[j]);
}
displayPics(gallery);
}
function displayPics(gallery) {
for (var i = 0; i < gallery.length; i++) {
document.getElementById('gallery').innerHTML += '' + '<img src="' + gallery[i] + '" alt="Gallery Image" />' + '';
}
}
var userFeed = new Instafeed( {
options
});
userFeed.run();
setTimeout(function() { snagImages() }, 500);
First off, I am just starting to learn javascript so your patience is appreciated. I have a problem that I am trying to figure out. I am looking for a way to be able to click an image, and then click the image I want to swap it with. To elaborate, I have 9 images labeled 0-9, and 9 blank images. My goal is to be able to click a numbered image and swap it for one of the blank images. All I have come up with is this, but it absolutely does not work in the way I need.
function swap1() {
element = document.getElementById('0')
if (element.src.match("0.jpg")) {
element.src = "blank.jpg";
alert(this.id)
} else {
element.src = "0.jpg";
}
}
<img id="img0" src="0.jpg" onclick="swap(this);">
<img id="img1" src="1.jpg" onclick="swap(this);">
<img id="img2" src="2.jpg" onclick="swap(this);">
<script>
function swap(d){
if (!d.osrc) d.osrc=d.src; //save the original src file
if (d.blanked){
d.src=d.osrc;
d.blanked=null;
} else {
d.blanked=true;
d.src='blank.jpg';
}
//un-blank the "other guys"
for (var i=0;i<3;i++){ //change the upper bound as you add more images
var obj=document.getElementById('img'+i);
if (obj==d) continue; //skip self
obj.blanked=null;
obj.src=obj.osrc;
}
}
</script>
The above code demonstrates two important techniques: a. passing in self-reference to avoid tedious naming; b. storing state variables in the DOM object
id can't start with a number. Change it to a valid id like image or just get the reference to the element via event.target.
Demo: http://jsfiddle.net/DerekL/b7C3H/
Try this. Say your html like
<img id="myimage" onclick="swap1()" src="0.jpg">
function swap1() {
element = document.getElementById('myimage');
if (element.src.match("0.jpg")) {
element.src = "blank.jpg";
} else {
element.src = "0.jpg";
}
}
Hey im having trouble with my javascript rollover. The image does not change. Ive had a look at some tutorials and i cant see where im going wrong.
Here is my code:
Home.xhtml
<img src="images/Weights.png" width="900" height="300" border="0" alt="Gym Equipment" name="gym"
onMouseOver="swapImage('gym','treadmill');" onmouseout="swapImage('gym','weights');"/>
newjs.js
// Pre load images for rollover
if (document.images)
{
treadmill = new Image
weights = new Image
treadmill.src = "images/Treadmill.png"
weights.src = "images/Weights.png"
}
function swapImage(thisImage,newImage)
{
if (document.images)
{
document[thisImage].src = eval(newImage + ".src")
}
}
How i tell the app where the js is:
document[thisImage].src = eval(newImage + ".src")
should be
document[thisImage].src = eval(newImage ).src
Please avoid using eval() as it is generally the slowest way to evaluate code and there are some circumstances where it introduces security risks depending upon where the data comes from that you're calling eval on.
You should be able to make this work:
HTML:
<img src="images/Weights.png" width="900" height="300" border="0" alt="Gym Equipment" name="gym"
onMouseOver="swapImage(this,'treadmill');" onmouseout="swapImage(this,'weights');"/>
Javascript:
// Pre load images for rollover
window.treadmill = new Image();
window.weights = new Image();
treadmill.src = "images/Treadmill.png"
weights.src = "images/Weights.png"
// this function must be defined globally
// (e.g. not defined inside any other function)
function swapImage(thisImage,newImageName) {
thisImage.src = window[newImageName].src;
}
Working demo here: http://jsfiddle.net/jfriend00/cv8tT/
Changes I made:
Removed the use of eval() and use window[name] to access global variables.
Changed the way swapImage() is called in the HTML to pass this so you can directly access the desired image.
Remove the if (document.images) checks since it is no longer used by the code.
FYI, all this could be done with CSS and background images with no javascript at all.
I would take a slightly different approach by taking the mouseover and mouseout attributes out of your image tag. This will help keep your code more maintainable.
I made a DEMO jsfiddle here
Note that I am using 3 images from Flickr, the default, one on mouseover, and one on mouseout. I hope this helps.
** Also note that the img tag now has an ID which is referenced in the bindings.
// Pre Load Images
var img1 = new Image();
var img2 = new Image();
img1.src = "http://farm4.staticflickr.com/3230/2953035318_b54956e7df_q.jpg";
img2.src = "http://farm4.staticflickr.com/3026/2992860864_aa9e8b0818_q.jpg";
// Event binding function
var bindEvent = function (el, eventName, eventHandler) {
if (el.addEventListener != null) {
return el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent != null) {
return el.attachEvent('on' + eventName, eventHandler);
}
}
// Mouseover binding
bindEvent(document.getElementById('surfer'), "mouseover", function (e) {
this.setAttribute("src", img1.src);
});
// Mouseout Binding
bindEvent(document.getElementById('surfer'), "mouseout", function (e) {
this.setAttribute("src", img2.src);
});
I tested the following code in IE, Chrome, and Firefox and it does not work in any of them. I have read several questions about similar problems but they have not offered solutions that fix my example.
I am trying to create a pause/play button that interfaces with JWplayer (I also want it to interface with flowplayer, once I get the button working) and the image will change depending on which image is currently there. I also have a stop button that stops the player completely and changes the image of the pause/play button to pause.
Here is my current code:
<script type="text/javascript">
function changeimg()
{
var obj = document.getElementById('image1');
var imgtag1 = '<img src=\'PLAY.png\'>';
var imgtag2 = '<img src=\'PAUSE.png\'>';
if(obj.innerHTML == imgtag2)
{obj.innerHTML = imgtag1;}
else
{obj.innerHTML = imgtag2;}
return;
}
function playimg()
{
document.getElementById('image1').innerHTML = '<img src=\'PLAY.png\'>';
return;
}
</script>
<div id="image1" href="#" onclick="changeimg(); jwplayer('mediaspace1').play(); jwplayer('mediaspace2').play(); jwplayer('mediaspace3').play(); jwplayer('mediaspace4').play();"><img src='PLAY.png'></div>
<div href="#" onclick="playimg(); jwplayer('mediaspace1').stop(); jwplayer('mediaspace2').stop(); jwplayer('mediaspace3').stop(); jwplayer('mediaspace4').stop();"><img src='STOP.png'></div>
The play/pause function works, and the first div WILL change into the pause img (so the javascript is going through) and it WILL change back into play if I click on the second div (stop function - triggers playimg() ) but it will not change back into the play image if I click on the pause button again.
For security reasons I can't link the website, but any help would be appreciated
It looks like all you really want to change is the SRC of the IMG tag, not necessarily the entire innerHTML. As machineghost mentions in his comment, there may be whitespace added or other changes to the full HTML that may make your comparison come out as false.
However, you could check if obj.src == "PLAY.png" and set the SRC attribute directly. Something like this:
function changeimg()
{
var obj = document.getElementById('image1');
var img1 = 'PLAY.png';
var img2 = 'PAUSE.png';
if(obj.src == img2)
{obj.src = img1;}
else
{obj.src = img2;}
return;
}
I think the innerhtml you are replacing in changeimg() is affecting the whole obj element, which is a div. So, if(obj.innerHTML == imgtag2) will return false since the div innerhtml is not imgtag2, but the next time you are going to call changeimg(), "obj" will be undefined because you replaced its innerhtml with an HTML code that doesn't have an id: {obj.innerHTML = imgtag2;}
Check the console to see if there's any javascript error, which it should, at if(obj.innerHTML == imgtag2)
rgds.
Just check whether PLAY is present or not and then change innerHTML according to it
function changeimg()
{
var obj = document.getElementById('image1');
var imgtag1 = '<img src=\'PLAY.png\'>';
var imgtag2 = '<img src=\'PAUSE.png\'>';
if(obj.innerHTML.indexOf('PLAY') != -1)
{obj.innerHTML = imgtag2;}
else
{obj.innerHTML = imgtag1;}
return;
}