I'm trying to make a function that I can use globally to create rollover states for images. Basically, I want to be able to add a class to an image, and then when you rollover it, jquery will use the same image name, and same extension, but add "-over" to the file name. (I'll have an image with the rollover state named the same as the non rolled over state except with the -over on it. I came up with this, but it's not working. Am I doing something wrong or does anyone know of a better way to do it?
$('.btn').hover(function(){
$(this).attr("src").split(".jpg").join("Over.jpg"));
});
image:
<img src="/static/images/overlay-close-button.jpg" alt="Close" title="Close" id="our-staff-overlay-close" class="btn"/>
Thanks!
EDIT: Is there any way to make it non specific to the file time, where it can figure out any file type rather than just jpgs?
I'm using:
$('.btn').hover(function(){
this.src = this.src.split(".jpg").join("Over.jpg");
}, function() {
this.src = this.src.split("Over.jpg").join(".jpg");
});
and it's working great
EDIT 2: Can I also add an active state (when the button is being clicked)?
The splitting and joining should work as intended, you just need to set that back to the src attribute of the img:
$('.btn').hover(function() {
var src = $(this).attr("src");
src = src.split('.jpg').join('-over.jpg');
$(this).attr("src", src);
});
Also, if you want it to work with any extension, you could use a regular expression like this:
$('.btn').hover(function() {
var src = $(this).attr("src");
src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2");
$(this).attr("src", src);
});
The regular expression matches anything that ends with a period followed by one of png, gif, jpg, or jpeg, and replaces it with the first part (the path + filename), the string "-over", a period, and the original extension.
You can replace it back to the original state by removing the -over from the source:
$('.btn').hover(function() {
var src = $(this).attr("src");
src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2");
$(this).attr("src", src);
}, function() {
var src = $(this).attr("src");
src = src.replace(/(.*)-over\.(png|gif|jpg|jpeg)$/, "$1.$2");
$(this).attr("src", src);
});
The jQuery().hover event accepts two functions, the first one is called when you start the hover, the second one is called when you exit the hover.
You're just not doing anything with the result. In this case you want to set the src (which can be done a few ways), here's the most efficient example (without changing your .split().join() method):
$('.btn').hover(function(){
this.src = this.src.split(".jpg").join("Over.jpg");
}, function() {
this.src = this.src.split("Over.jpg").join(".jpg");
});
$('.btn').hover(function(){
$(this).attr("src", this.src.split(".jpg")[0] + "-over.jpg");
}, function() {
$(this).attr("src", this.src.split("-over.jpg")[0] + ".jpg");
})
You may want to consider achieving your rollover effect using pure CSS. It's really not necessary to involve script in something as trivial as a image rollover. Plus, a pure CSS approach will still work for the paranoids out there who browse with script turned off.
Use the :hover and :active pseudoclasses and take advantage of CSS sprites.
The downside here is that this method is harder to make generally applicable because you need to know the size of your images before-hand.
Related
My CMS produces an img src="(unknown)" if an image isn't provided in the database. I would like to use javascript when this occurs to change it to img src="/images/missing.png"
As a complete JS noob I have tried several hacks but none seem to work... any ideas? (there is likely to be more than one image on the page if that makes any difference)
This should work for you, if you use onError event for handling missing image src
<img src="main_img.png" onError="this.onerror=null;this.src='/images/missing.png';" />
I used this to solve a similar problem I had (using javascript)...
const images = document.querySelectorAll("img");
images.forEach((image) => {
let imgsrc = image.getAttribute("src");
if (imgsrc === "") {
image.src = "/images/missing.png";
}
});
if you're using php then this problem is going happen for sure you can use esc_url($url)
esc_url function solves the problem
If you're dynamically injecting the src when the page loads, you can always check and swap with placeholder if needed.
if (imgSrc === "unknown") {
imgSrc = "placeholder.png";
}
<img src="img/image1.png" id="mainimage">
<p>Dog</p>
<p>Cat</p>
I am trying to use JavaScript/jQuery so that whenever a user places their mouse over any of the links with the id's pet1 & pet2 it will change the image src of the image with the id of mainimage.
var img = document.getElementById('swap');
document.getElementById('pet1').onmouseover = function(){
// manipulate the image source here.
img.src = img.src.replace(/\.jpg/, '-on.jpg');
}
The above JavaScript is a script I found here that seems to have the functionality I am looking for. The only problem is that whenever my mouse is over the link it does not display the image I want. Ok, the question I am looking for is how can I make the image with the source (img/pet1.jpg) appear?
Any help will be appreciated!
Try this more simply
$(function() {
$("#pet1")
.mouseover(function() {
var src = 'first image path';
$("#mainimage").attr("src", src);
})
.mouseout(function() {
var src2 ='Default image path';
$(this).attr("src", src2;
});
});
Similllar for second image and for shortening even this you can give a class to every link you want and then by using $(element).each() function and "data" attribute of html5 you can manage it in more cool way
This should get you started.
For all links at once we set a mouseover handler (which takes the ID of the link, turns it into a path to the image, and displays it) and a mouseout handler (which reverts the image's src to its original image).
$(document).ready(function() {
// To start with, get a reference to the image and its original src
var $mainImage = $('#mainimage'),
originalImageSrc = $mainImage.attr('src');
// Then add mouseover and mouseout handlers to all the links
$('a')
.on('mouseover', function() {
var newImageSrc = 'img/' + $(this).attr('id') + '.jpg';
$mainImage.attr('src', newImageSrc);
})
.on('mouseout', function() {
$mainImage.attr('src', originalImageSrc);
});
});
You can see it working in this JSFiddle. So that you can see it working in the JSFiddle without real images, I've used a div's text rather than an img's src, but that's just for the demo.
Of course you could always adapt it (maybe you want to be more specific than all a tags, and maybe you don't always want to use the format img/<id>.jpg – in which case you could add a data-img-src attribute to all your links and use .data('imgSrc') instead of the .attr('id')).
Hopefully this is what you're looking for.
HTML:
<img src="http://placehold.it/300x150" id="theImage">
<p>Red</p>
<p>Blue</p>
JS:
$('.yourClass').hover(function() {
var newImg = $(this).data('img');
$('#theImage').attr('src',newImg)
}, function() {
$('#theImage').attr('src','http://placehold.it/300x150')
});
JSFiddle
Right now I am building a map of the US, and when you hover over any given state, I am replacing the image with an image of a different color.
My problem is that the way I am currently doing things, the image is being replaced and a new image loaded on hover.
I have the HTML laid out as:
<img class="state" id="alaska" src="img/united-states_Alaska.png" alt="alaska">
<img class="state" id="hawaii" src="img/united-states_hawaii.png" alt="hawaii">
And the jQuery I am using is:
$('.interactive-map img').each(function(e){
var src = $(this).attr('src');
$(this).hover(function(){
$(this).attr('src', src.replace('.png', '-hover.png'));
}, function(){
$(this).attr('src', src);
});
});
I am curious if there is another way to either preload the images with JavaScript, or make it so that there isn't a new request for image every time I hover. I would like to not have to change the HTML or CSS much and optimize it in JavaScript.
Add your images to the DOM on page load but in hidden state, then they get cached
$(function() {
var images = ['url/to/your/jpg1.jpg', 'ur/to/your/png2.png'];
var d = document.createElement("div");
d.style.display = 'none';
document.body.appendChild(d);
for (var i in images)
{
var img = document.createElement("img");
img.src = images[i];
d.appendChild(img);
}
});
Have two image tags and set the first image's display: block. Set the second image's display: none.
Then on hover you switch the them. It is as easy as that.
Use PreloadJS
Example:
var preload = new createjs.LoadQueue();
preload.addEventListener("fileload", handleFileComplete);
preload.loadFile('http://createjs.com/images/404/gBot-confused.jpg');
function handleFileComplete(event) {
document.body.appendChild(event.result);
}
Full Docs: here
Another interesting post using JS and AJAX: Preloading
I have the following script which take a string with html information (containing also reference to images).
When I create a DOM element the content for the image is being downloaded by the browser. I would like to know if it is possible to stop this Beauvoir and temporary prevent loading.
I am targeting web-kit and presto browsers.
relativeToAbosluteImgUrls: function(html, absoluteUrl) {
var tempDom = document.createElement('div');
debugger
tempDom.innerHTML = html;
var imgs = tempDom.getElementsByTagName('img'), i = imgs.length;
while (i--) {
var srcRel = imgs[i].getAttribute('src');
imgs[i].setAttribute('src', absoluteUrl + srcRel);
}
return tempDom.innerHTML;
},
Store the src path into an HTML5 data-* attribute such as data-src. Without src being set, the browser will not download any images. When you are ready to download the image, simply get the URL from the data-src attribute and set it as the src attribute
$(function() {
// Only modify the images that have 'data-src' attribute
$('img[data-src]').each(function(){
var src = $(this).data('src');
// modify src however you need to, maybe make
// a function called 'getAbsoluteUrl'
$(this).prop('src', src);
});
});
The approach taken by popular image library, Slimmage, is to wrap your img tags in noscript tags:
<noscript class="img">
<img src="my-image.jpeg" />
</noscript>
Web scrapers and people with JS turned off will see the image as if the noscript wasn't there but other browsers will completely ignore the noscript and img tags.
You can then use JavaScript to do whatever you want with it, for example (using jQuery):
$('noscript.img').replaceWith(function(){
return $(this.innerText).removeAttr('src');
});
I think you should reverse the logic, don't load the images by default and at the moment the image is needed, update it's src attribute to tell browser to start loading.
Or even better way would be to use some jquery lazy image loading plugin like this one:
http://www.appelsiini.net/projects/lazyload
Hope this helps.
To prevent images from being show, you could use this.
$(window).loaded( function() {
$("img").removeAttr("src");
});
It might be tricky and give unexpected results, but it does it.
I load png image generated by server-side PHP script (chart) to the HTML IMG-element <img id="chart"> using following JS code:
$('#chart').attr('src', 'chart.php');
The PNG-image generation and downloading takes about 1 second, so I want to show gif loader while image is loading. How to implement this feature with JS?
For balance this is very simple to do in plain JS:
var preload = function(element, src) {
var img = new Image();
// Apply onload before applying src attribute to avoid IE prematurely firing
img.onload = function() {
// Replace #chart with image
element.parentNode.replaceChild(img, element);
};
img.src = src;
}
preload(document.getElementById('chart'), 'chart.php?_...');
$('#chart').attr('src', 'chart.php').load(function(){
//something
});
In case the browser caches it, you may way to add something to the query string to break that. Either way, you need to listen for the image's load event, which should be bound before setting its src (in case it's cached):
var target_url = 'chart.php?_=' + (new Date()).getTime();
// Show "loading"
$('#chart').on("load", function () {
// Hide "loading"
}).attr('src', target_url);
Reference:
http://api.jquery.com/load-event/
Note the caveats near the bottom of that reference, referring to the event when working with images:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache