I have a load of social buttons (<img>s in a <ul>) on the right-handle side of my site.
They might have filenames such as google.png, or twitter.png.
I now want to change the src on hover to google_b.png or twitter_b.png - and I will consistently be naming my files in this way for all of them.
My question is how can I easily change the filenames to and from the _b (maintaining the file extension) without having to predifine the filenames?
At the moment my code looks like this:
$('#social li').hover(function() {
// hover in
// a bunch of code to animate a tooltip is here
var $img = $t.children('img'),
src = $img.attr('src');
// change the source to img_b.png
$img.attr('src', src);
},
function() {
// hover out
var $img = $(this).children('img'),
src = $img.attr('src');
// remove _b to make it img.png again
$img.attr('src', src);
});
Assuming files won't have fake extensions (image.png.jpeg) just split the src on ., add _b to second to last part and join again on ..
src = $img.attr('src');
var temp = src.split(".");
temp[temp.length - 2] += "_b"; //change second to last element of array
src = temp.join(".");
$('#social li').hover(function() {
// hover in
// a bunch of code to animate a tooltip is here
var $img = $t.children('img'),
src = $img.attr('src').replace(".png", "_b.png");
// change the source to img_b.png
$img.attr('src', src);
},
function() {
// hover out
var $img = $(this).children('img'),
src = $img.attr('src').replace("_b.png", ".png");
// remove _b to make it img.png again
$img.attr('src', src);
});
You could use the data function in jQuery to store the info so you won't have to constantly recalculate it.
$('#social li img').each(function(){
var image = this.src.split(".");
var onImage = image[0] + "_b." + image[1];
$(this).data("onImage",onImage);
$(this).data("offImage",this.src);
}).hover(function(){
this.src = $(this).data("onImage");
},function(){
this.src = $(this).data("offImage");
});
You could extract the src attribute directly from each image using the jquery attr() function, append characters to it like '_b' and is it on hover.
Related
I have original image src in data-attr my element. I want get height this image. But I don't want append image to DOM. How I can get height? My code:
const imgSrc = $target
.closest('.js-photo-item')
.find('.photos__img--value')
.data('original-image');
const $img = $(new Image()).attr('src', imgSrc);
console.log($img.height()) // this return 0
const imgSrc = $target
.closest('.js-photo-item')
.find('.photos__img--value')
.data('original-image');
const $img = $(new Image()).attr('src', imgSrc);
$img.on('load', () => {
console.log($img[0].height) // return height img
});
Thanks George P user. His answer above...
You need to wait for the image to load first instead of trying to check the height right away. See, for example, https://stackoverflow.com/a/14134416/922613
I am using Materialize CSS and have the "Material Box" which is a lightbox plugin. I want all of the thumbnails to be the same size. When clicked I want the full photo to load.
I am using onclick to change the src. How do I change it back to the thumbnail when the large photo closes (either with a click or the escape key)?
<div class="col s6 m3">
<img class="materialboxed responsive-img" src="images/thumb1.jpg" onclick='this.src="images/photo1"'>
</div>
Material Box Javascript
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.materialboxed');
var options = {}
var instances = M.Materialbox.init(elems, options);
});
// Or with jQuery
$(document).ready(function(){
$('.materialboxed').materialbox();
});
Materializecss.com - https://materializecss.com/media.html
I haven't found an easy other way of achieving the lightbox effect with cropped square thumbnails. Any advice would be greatly appreciated!
Here is one implementation of what you want, keeping track of the image click state.
$(document).ready(function(){
$('.materialboxed').materialbox();
// Image sources
const srcThumb = '/images/thumb1.jpg'
const srcPhoto = '/images/photo1.jpg'
// Click state
var clicked = false
// Get image element and bind click event
const img = $('.materialboxed')
img.on('click', function() {
img.attr('src', clicked ? srcPhoto : srcThumb)
clicked = !clicked
})
});
No need to rely on onclick in this case.
Materialize is already binding onclick for those images.
And it provides the following native methods we can use for doing exactly what you want using pure JS (no jQuery):
onOpenStart Function null Callback function called before materialbox is opened.
onCloseEnd Function null Callback function called after materialbox is closed.
In this example below, we assume there is a normal materialboxed photo gallery containing thumbnails named thumb_whatever.jpg, for example. But we're also serving the original sized photo named whatever.jpg in the same directory.
Then we're changing src attribute dynamically removing the thumb_ prefix to get the original image, which in this case will be imediately lightboxed by materialize.
And after closing the lightbox, the src attribute is being set back again without the thumb_ prefix.
We do that while initializing Materialbox:
// Initializing Materialbox
const mb = document.querySelectorAll('.materialboxed')
M.Materialbox.init(mb, {
onOpenStart: (el) => {
var src = el.getAttribute('src') // get the src
var path = src.substring(0,src.lastIndexOf('/')) // get the path from the src
var fileName = src.substring(src.lastIndexOf('/')).replace('thumb_','') // get the filename and removes 'thumb_' prefix
var newSrc = path+fileName // re-assemble without the 'thumb_' prefix
el.setAttribute('src', newSrc)
},
onCloseEnd: (el) => {
var src = el.getAttribute('src') // get the src
var path = src.substring(0,src.lastIndexOf('/')) // get the path from the src
var fileName = src.substring(src.lastIndexOf('/')).replace('/', '/thumb_') // get the filename and adds 'thumb_' prefix
var newSrc = path+fileName // re-assemble with the 'thumb_' prefix
el.setAttribute('src', newSrc)
}
})
This solution is also working like a charm for me, crossplatform.
Hi im building a slider using jquery tools.. here is my code http://jsfiddle.net/SmW3F/5/
Anyway, the problem is when you over the image is updated (the Main image) so each thumb update the main image on hover.
The problem is the title is just working for 1st item.. all other items are not updating the title..
here is this part of the code
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
$(".items img").on("hover",function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("_t", "");
var tbtit = $("#tbtit").html();
var tbdesc = $("#tbdescp").html();
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").stop(true, true).fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap.find(".img-info h4").replaceWith(tbtit);
wrap.find(".img-info p").replaceWith( tbdesc);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").trigger("mouseover");
var count = 0;
var scroll_count = 0;
setInterval(function(){
count++; // add to the counter
if($(".items img").eq(count).length != 0){
console.log(count);
$(".items img").eq(count).trigger("mouseover");
if(count % 5 === 0)
{
I found a couple of issues with your script, but first you have invalid markup in your page since you have multiple <div> elements with the same ids of tbtit and tbdescp. Id attributes should be unique in a HTML page so should change those to classes instead.
Now in your script you need to change the part where you retrieve the values of the title and the description of the image that is hovered to reference the sibling elements:
//THIS
var tbtit = $("#tbtit").html();
var tbdesc = $("#tbdescp").html();
//SHOULD NOW BE THIS
var tbtit = $(this).siblings('.tbtit').text();
var tbdesc = $(this).siblings('.tbdescp').text();
Finally when you update the text for your main image you want to set the content for your <h4> and <p> tags and not replace them completely, so use .text()
//THIS
wrap.find(".img-info h4").replaceWith(tbtit);
wrap.find(".img-info p").replaceWith( tbdesc);
//SHOULD NOW BE THIS
wrap.find(".img-info h4").text(tbtit);
wrap.find(".img-info p").text( tbdesc);
Any One Know Tell me the suggestion to do this. How can i check if the anchor href attribute contain image path or some other path.
For Example:
<img src="image.jpg"/>
<img src="image.jpg"/>
See the above example shows href attribute contain different path like first one is the image and second one is the some other site link. I still confuse with that how can i check if the href path contain the image path or some other path using jquery or javascript.
Any suggestion would be great.
For example (you may need to include other pic formats if needed):
$("a").each(function(i, el) {
var href_value = el.href;
if (/\.(jpg|png|gif)$/.test(href_value)) {
console.log(href_value + " is a pic");
} else {
console.log(href_value + " is not a pic");
}
});
Jquery:
$(document).ready( function() {
var checkhref = $('a').attr('href');
var image_check = checkhref.substr(checkhref.length - 4)
http_tag = "http";
image = [".png",".jpg",".bmp"]
if(checkhref.search("http_tag") >= 0){
alert('Http!');
//Do something
}
if($.inArray(image_check, image) > -1){
alert('Image!');
//Do something
}
});
you may check if image exists or not, without jQuery
Fiddle
var imagesrc = 'http://domain.com/image.jpg';
function checkImage(src) {
var img = new Image();
img.onload = function() {
document.getElementById("iddiv").innerHTML = src +" exists";
};
img.onerror = function() {
document.getElementById("iddiv").innerHTML = src +"does not exists";
};
img.src = src; // fires off loading of image
return src;
}
checkImage(imagesrc);
I am trying to replace the img source of a given source using jQuery. For example, when the image src is smith.gif, replace to johnson.gif. If williams.gif replace to brown.gif etc.
EDIT: The images are retrieved from an XML to a random order, without class to each .
This is what I tried:
if ( $("img").attr('src', 'http://example.com/smith.gif') ) {
$(this).attr('src', 'http://example.com/johnson.gif');
}
if ( $("img").attr('src', 'http://example.com/williams.gif') ) {
$(this).attr('src', 'http://example.com/brown.gif');
}
Note that my HTML has many images. For example
<img src="http://example.com/smith.gif">
<img src="http://example.com/williams.gif">
<img src="http://example.com/chris.gif">
etc.
So, how can I replace the images: IF img src="http://example.com/smith.gif" then show "http://example.com/williams.gif". etc...
Thanks alot
This is what you wanna do:
var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.
http://api.jquery.com/attr/
A better way to approach replacing a series of images source would be to loop through each and check it's source.
Example:
$('img').each(function () {
var curSrc = $(this).attr('src');
if ( curSrc === 'http://example.com/smith.gif' ) {
$(this).attr('src', 'http://example.com/johnson.gif');
}
if ( curSrc === 'http://example.com/williams.gif' ) {
$(this).attr('src', 'http://example.com/brown.gif');
}
});
In my case, I replaced the src taq using:
$('#gmap_canvas').attr('src', newSrc);