Javascript: onmouseover function - javascript

I have a problem with changing onmouseover and onmouseout attributes on dynamic pictures. The way i want it to work is whenever i put my mouse over images the images must change and when i take my mouse away it must be changed to the original picture. and whenever i select any image, that image must be changed to the image which was displayed while moving the mouse across the image. and when i select any other image the same process must take place but the previous image that was changed must be changed back to the original picture.
I have accomplished all of the above but my problem is when i select multiple pictures and put my mouse over images that were previously selected, those images do not change (onmouseover attribute does not work on them anymore).
<script language="javascript">
function changeleft(loca){
var od=''
var imgs = document.getElementById("leftsec").getElementsByTagName("img");
for (var i = 0, l = imgs.length; i < l; i++) {
od=imgs[i].id;
if(od==loca){
imgs[i].src="images/"+od+"_over.gif";
imgs[i].onmouseover="";
imgs[i].onmouseout="";
}else{
od = imgs[i].id;
imgs[i].src="images/"+od+".gif";
this.onmouseover = function (){this.src="images/"+od+"_over.gif";};
this.onmouseout = function (){this.src="images/"+od+".gif";};
}
}
}
</script>
<div class="leftsec" id="leftsec" >
<img id='wits' class="wits1" src="images/wits.gif" onmouseover="this.src='images/wits_over.gif'" onmouseout="this.src='images/wits.gif'" onclick="changeleft(this.id)" /><br />
<img id='city' class="city1" src="images/city.gif" onmouseover="this.src='images/city_over.gif'" onmouseout="this.src='images/city.gif'" onclick="changeleft(this.id)" /><br />
<img id='organise' class="city1" src="images/organise.gif" onmouseover="this.src='images/organise_over.gif'" onmouseout="this.src='images/organise.gif'" onclick="changeleft(this.id)" /><br />
<img id='people' class="city1" src="images/people.gif" onmouseover="this.src='images/people_over.gif'" onmouseout="this.src='images/people.gif'" onclick="changeleft(this.id)" /><br />
</div>

I would recommend to use an Ajax library (jQuery, YUI, dojo, ExtJS, ...). In jQuery I would do something like:
Edit: Extended the example with .click() ability.
var ignoreAttrName = 'data-ignore';
var imgTags = jQuery('#leftsec img'); // Select all img tags from the div with id 'leftsec'
jQuery(imgTags)
.attr(ignoreAttrName , 'false') // Supplying an ignore attribute to the img tag
.on('click', function () {
jQuery(imgTags).attr(ignoreAttrName, 'false'); // Resetting the data tag
jQuery(this).attr(ignoreAttrName, 'true'); // only the current will be ignored
// Do whatever you want on click ...
})
.on('mouseover', function () {
// This will be called with the img dom node as the context
var me = jQuery(this);
if (me.attr(ignoreAttrName) === 'false') {
me.attr('src', me.attr('id') + '.gif');
}
})
.on('mouseout', function () {
// This will be called when leaving the img node
var me = jQuery(this);
if (me.attr(ignoreAttrName) === 'false') {
me.attr('src', me.attr('id') + '-over.gif');
}
});
With a library it's cleaner and more scalable I think and the chance that it's working in other browsers is increased too :).
Hope this helps you out!

Related

Toggle image source with jQuery

I want to do something interesting, so for example i have an image on my website and i want to change it when a button is triggered, but then i want to revert it back to the original when the button is clicked again (or add the same img to it) and repeat this all the time when the event is clicked. How can I achieve this ?
Here is my current Jquery but only that works for one time click
$('#menu-btn').on({
'click': function () {
$('#div1').attr('src', 'images/card-light.png');
}
});
Html code
<button id="menu-btn">click me</button>
<img id="div1" src="./images/card-dark.png">
Assets
images/card-dark.png
images/card-light.png
On document load, store the image source in a variable. In our case, it's called prev.
Inside the toggle function, we check whether the source of the image is equal to the source when it was loaded. If it was, we change the source to another image. When the source is changed and we call the toggle function again, we know that the source is different from the previous one, so we revert it back to the original source.
$(document).ready(function() {
var img = $('#img');
var prev = img[0].src;
function toggle(img) {
let src = img.src;
if (src == prev) {
img.src = "https://pbs.twimg.com/profile_images/453956388851445761/8BKnRUXg_400x400.png";
img.height="48";
} else {
img.src = prev;
}
}
$('button').on('click', function() {
toggle(img[0]);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" height="48"></script>
<img id="img" src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
<button>Toggle</button>
We can take it a step further by using data attributes to store the two sources so you can easily extend this for multiple images.
$(document).ready(function() {
var img = $('#img');
var prev = img[0].src;
function toggle(i) {
let src = i[0].src;
let dsrc = i.data('switch-with');
if(dsrc==src){
i[0].src=prev;
}else{
i[0].src=dsrc;
i[0].height="48";
}
}
$('button').on('click', function() {
toggle(img);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" height="48"></script>
<img id="img" src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1" data-switch-with="https://pbs.twimg.com/profile_images/453956388851445761/8BKnRUXg_400x400.png">
<button>Toggle</button>

Implementing mouseover/mouseout for many images in an external JavaScript file

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">

Load content in div from a href tag in jQuery

I want to load all images before displaying them in a slideshow. I have been searching a lot but nothing seems to work. This is what i have so far and it doesn't work. I am loading images from the <a> tag from another div.
$('.slideshow').load(function(){
if (loaded<length){
first = $(settings.thumb).eq(loaded).find('a').attr("href");
$('<img src="'+first1+'"/>').appendTo('.slideshow');
}
else{ $('.slideshow').show(); }
loaded++;
});
Add an event listener to each image to respond to when the browser has finished loading the image, then append it to your slideshow.
var $images = $("#div_containing_images img");
var numImages = $images.length;
var numLoaded = 0;
var $slideshow = $(".slideshow");
$images.each(function() {
var $thisImg = $(this);
$thisImg.on("load", function() {
$thisImg.detach().appendTo($slideshow);
numLoaded++;
if (numLoaded == numImages) {
$slideshow.show();
}
});
});
It's a good idea to also listen for the error event as well, in case the image fails to load. That way you can increase numLoaded to account for broken image. Otherwise, your slideshow will never be shown in the event the image is broken.
Also note, that by calling detach() followed by appendTo() I am am moving the image in the DOM. If instead, you want to copy the image, use clone() instead of detach().
* EDIT TO MODIFY USER'S EXACT USE CASE *
var $images = $("li.one_photo a");
var numImages = $images.length;
var numLoaded = 0;
$images.each(function() {
$('<img />',
{ src: $(this).attr("href") })
.appendTo('.slideshow')
.on("load error", function() {
numLoaded++;
if(numLoaded == numImages) {
$('.slideshow').show();
}
});
});
* EDIT #2 *
Just realized you were putting everything in the $(".slideshow").load() function. Since $(".slideshow") represents a DIV, it will never raise a load event, and the corresponding function will never execute. Edited above accordingly.

Toggle image src attribute using Javascript

I am trying to change the HTML image src using Javascript. I have two images Plus.gif and Minus.gif.I have inserted HTML img tag and have written a Javascript function to change the image src when clicked.
Problem is that I want to change it back again when user clicks on the image.
For example when the page is loaded the Plus.gif shows and when user clicks on it the image it changes to Minus.gif.
I want it so, when the image is Minus.gif and user clicks on it this should be changed to Plus.gif.
Here is my Javascript function:
<script language="javascript" type="text/javascript">
function chngimg() {
var img = document.getElementById('imgplus').src; //= 'Images/Minus.gif';
if (img) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
} else if (!img) {
document.getElementById('imgplus').src = 'Images/Plus.gif';
alert(img);
}
}
</script>
Image tag:
<img id="imgplus" alt="" src="Images/Plus.gif" onmouseover="this.style.cursor='pointer'" onclick="chngimg()" />
See the changes I made to make it working
<script language="javascript" type="text/javascript">
function chngimg() {
var img = document.getElementById('imgplus').src;
if (img.indexOf('Plus.gif')!=-1) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
}
else {
document.getElementById('imgplus').src = 'Images/Plus.gif';
}
}
</script>
<img id="imgplus" alt="" src="Images/Plus.gif" onmouseover="this.style.cursor='pointer'" onclick="chngimg()" />
Hope that resolves your question.
One way would be to add a toggle variable in your function:
var toggle = false;
function chngimg() {
if (toggle === true) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
} else {
document.getElementById('imgplus').src = 'Images/Plus.gif';
alert(img);
}
toggle = !toggle;
}
Note that it's a better practice to use a sprite for this kind of thing. If you're using two images, the user experience is going to be clunky, because the first time they click the image, there will be a slight delay while the second image loads.
Ideally you would have the two images as a sprite sheet, and be using JQuery. Then you could just do it like this.
HTML
<img id="imgplus" src="Images/Sprite.gif" onclick="chngimg()" />
CSS
#imgplus .clicked { background-position: 0 -30px; }
Javascript
function chngimg() {
$("#imgplus").toggleClass("clicked");
}
I have successfully used this general solution in pure JS for the problem of toggling an img url:
function toggleImg() {
let initialImg = document.getElementById("img-toggle").src;
let srcTest = initialImg.includes('initial/img/url');
let newImg = {
'true':'second/img/url',
'false':'initial/img/url'}[srcTest];
return newImg;
}
Then call toggleImg() inside whatever event handler you use....
someButton.addEventListener("click", function() {
document.getElementById("img-toggle").src = toggleImg();
}

Javascript - swap image on click or rollover

I know how to do this in jquery but i am trying to do the below in pure old school javascript. Can someone help:
$(".thumbnail").click(function() {
$("#mainImage").attr("src", $(this).attr("src"));
});
My ultimate goal is to click on a thumbnail and have the main image change but I need to do it in javascript (no jquery). I know this sounds pretty simple but I cannot figure it out. thank you.
There are so many things that jQuery gives you automatically that it's difficult to give you an answer that will do everything that your jQuery code does. Here is a simple example that will find every image with a class of thumbnail and set its onclick property to an event handler that performs an image swap.
onload = function () {
var bigImg = document.getElementById("mainImage");
for (var i = 0; i < document.images.length; i++) {
var img = document.images[i];
if (/\bthumbnail\b/.test(img.className) {
img.onclick = thumbnailHandler;
}
}
function thumbnailHandler(e) {
bigImg.src = this.src;
}
};
If you don't have to support IE7, you can simplify it slightly by using document.querySelectorAll():
onload = function () {
var bigImg = document.getElementById("mainImage");
var thumbs = document.querySelectorAll(".thumbnail");
for (var i = 0; i < thumbs.length; i++) {
thumbs[i].onclick = thumbnailHandler;
}
function thumbnailHandler(e) {
bigImg.src = this.src;
}
};
As an aside, I don't understand why you are setting the source of the main image to be the source of the thumbnail. Are you loading the full image into the thumbnail? That can be a lot to download and can quickly increase the memory footprint of your page.
Event delegation is probably the easiest way:
function expandThumbnail(e) {
if(~(' ' + e.target.className + ' ').indexOf(' thumbnail ')) {
document.getElementById('mainImage').src = e.target.src;
}
}
if(document.addEventListener) {
document.addEventListener('click', expandThumbnail, false);
} else {
document.attachEvent('onclick', function() {
expandThumbnail({
target: event.srcElement
});
});
}
If I understand right, you have a thumbnail image displayed, let's say '1thumb.png', of an associated image, let's say '1.png', and when you click this thumbnail image you want to change the src attribute of a main image, let's say with id='mainimg', to show the '1.png' image associated to the thumbnail instead of whatever it's showing. I tried this and it works:
Inside your <header>:
<script type='text/javascript'>
function myHandler(source){
document.getElementById('mainimg').src=source;
}
</script>
...
Your thumbnail code:
<img src='1thumb.png' onclick="myHandler('1.png')"/>
or, for rollover triggering:
<img src='1thumb.png' onmouseover="myHandler('1.png')"/>
Check it out: http://jsfiddle.net/d7Q27/7/

Categories

Resources