Jquery: Get each image src - javascript

I have a series of images each with the class "photo";
I want to go through each of these and retrieve the photo source, for use later in an if statement. I have written the below code to do this, but have not been successful:
$.each($(".photo"), function() {
var imgsrc = $(this).attr("src").length;
console.log(imgsrc);
});
I am not sure where I have gone wrong here. It seems to make sense to me, but I dont get anything in the console.
Can anyone point me in the right direction?

If you have given same class name for all img tag then try this ,
$(".photo").each(function() {
imgsrc = this.src;
console.log(imgsrc);
});

$(document).ready(function(){
$(".photo").each(function() {
imgsrc = this.src;
console.log(imgsrc);
});
});

May be you are missing doc ready handler:
$(function(){
$.each($(".photo"), function() {
var imgsrc = $(this).attr("src").length;
console.log(imgsrc); // logging length it should now print the length
});
});
make sure to load this script first then your $.each() function:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

You are trying to read the lenght of an object / array out of context here :
var imgsrc = $(this).attr("src").length;
change to
var imgsrc = $(this).attr("src");
edit : in order to check if the attribute exists
if (imgsrc == undefined) { /* do something */ }

Related

Trying to change the src of an image using sessionStorage

I have 2 html pages with an image on each one. I need to be able to click the image on the 2nd page and have it redirect me to the 1st page - with the first image.src changed to that of the second.
What is the best/correct way to do this? I have been trying to do it by storing the src in sessionStorage but it does't seem to be working. Here is the code for setItem:
<script type="text/javascript">
$('.images').on('click', '.groupOne', function(){
var image = $(this).find("img"); // selects images inside group
var imageSrc = img.first().attr("src"); // get src of first image
sessionStorage.setItem("choice", imageSrc);
window.location.href = 'firstPage.html';
});
</script>
And then to change the first image I need to use getItem:
<script type="text/javascript">
$(document).ready(function() {
var imgTwo = sessionStorage.getItem("choice");
var imgOne = document.getElementById("pageOneImage");
imgOne.src = imgTwo; //sets src of img1 to src of img2
});
</script>
But this doesn't seem to be working. Is there an easier way to do this using more jQuery? Thank you!
Maybe not the best solution, but how about adding the src as a param to the query string?
On the second page:
window.location.href = 'firstPage.html?src=' + src;
And the first page:
var reg = new RegExp("(^|&)src=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
var src = r != null ? unescape(r[2]) : null;
Now you got the src, if redirecting from the second page.

Populate an input field with an image src in javascript

I have an XHR response that returns images. I have my function in order to show the images. I am combining JQuery and JS in the same code snippet. So far all is working well:
function resultat(o){
var leselements = o.query.results.bossresponse.images.results.result;
var output = '';
var no_items = leselements.length;
for(var i=0;i<no_items;i++){
var lien = leselements[i].url;
//place image urls in img src
output += "<img src='" + lien + "' class='imgs'>";
}
// Place images in div tag
document.getElementById('results').innerHTML = output;}
But I would like to allow users to click an image and then populate an input field ('#imageurl') with the clicked image src. Here is what I tried but it does not work.
$('.imgs img').click(function(){
$('#imageurl').val() = "";
var source = $(this).attr('src');
$('#imageurl').val() = source;
});
Any help will be greatly appreciated. TIA.
Using .val() in this way will just return the current value of #imageurl.
$('#imageurl').val()
.val is a function call that works as a getter and a setter.
To set the value, try this:
$('#imageurl').val(source);
$('#imageurl').val("");
// ...
$('#imageurl').val(source);
See the documentation.
Try this:
$('img.imgs').click(function(){
var src = $(this).attr('src');
$('#imageurl').val(src);
});
If the image will be rendered after the attachment of the event handler use this:
$('img.imgs').live('click', function(){
var src = $(this).attr('src');
$('#imageurl').val(src);
});
Thank you guys for your prompt answers. I tried all of them but they did not work for me. I then asked a friend and we finally found a way to make it work. Probably not the best or professional way but it works. Here is the solution if ever anyone needs it.
function resultat(o){
var leselements = o.query.results.bossresponse.images.results.result;
var output = '';
var no_items = leselements.length;
for(var i=0;i<no_items;i++){
var link = leselements[i].url;
//Place urls in image src and pass in 'link' parameter to the getsrc function
output += "<img src='" + link + "' onclick='getsrc(\""+link+"\")'>";
}
// Place images in div tag
document.getElementById('results').innerHTML = output;
}
function getsrc (link) {
//console.log($(this));
$('#imageurl').val("");
// var source = $(this).attr('src');
//place imageurl value by passing in the link parameter.
$('#imageurl').val(link);
}

Check if an element has a background-image with pure JS?

What is the correct way to check if a particular element has a background-image associated with it, in pure Javascript?
Right now I have this:
var elementComputedStyle = window.getComputedStyle(element);
var hasBGImage = elementComputedStyle.getPropertyValue('background-image') !== 'none'
What you have works, but there are alternate ways of finding the property that you might find easier. I don't believe there is a single 'correct' way to do it, however.
Just javascript:
var hasBGImage = element.style.backgroundImage !== '';
Using jQuery:
var hasBGImage = $(element).css('background-image') !== 'none';
Make sure you declare the background image "inline", otherwise .style.backgroundImage won't work.
<script>
window.onload=function() {
var bg = document.getElementById('el').style.backgroundImage.length!=0;
alert(bg);
}
</script>
<div id='el' style="background-image: url('a.jpg');"></div>
If you can use inline CSS, that's the way. If, for some reason, you can't use that, let me know, I'll try to find out something else :)
I used this code in last one project and works perfect
// Check all background images exists
var imageURLs = $('.image-container ');
imageURLs.each(function(index, element){
var imageURL = $(element).css('background-image').replace('url("', '').replace('")', '');
var img = new Image();
img.onerror = function() { $(element).css('background-image','url(/build/images/missing-image.svg)'); };
img.src = imageURL;
});

How to insert first image if no others selected

I am trying to figure out a way to insert the first image of a jquery gallery once it's loaded basically.
I've searched everywhere and can't seem to find anything. I have pasted the code that works so far below. I think I have to put something like:
$(function() {
$(".image").click(function() {
var image = $(this).attr("rel");
var title = $(this).attr("alt");
var description = $(this).attr("content");
$('#gallery').hide();
$('#gallery').fadeIn('slow');
$('#image').html('<img src="' + image + '"/>');
return false;
});
});
use .append
example
$(".image").click(function() {
var img = $('<img/>');
img.attr("src", $(this).attr("rel") );
var title = $(this).attr("alt");
var description = $(this).attr("content");
$("#gallery").append( img );
$('#gallery').fadeIn('slow');
return false;
});
This will also append other images once their respective links been clicked.

How to get the src of a clicked image with prototype

I am struggling to get the image src of a image when its clicked. I just need the jQuery(this).attr("src") but in prototype, this.readAttribute doesn't work. I get: “this.readAttribute is not a function”
$$('.more-views > ul > li > img').invoke('observe', 'click', this.updateImage.bind(this));
updateImage: function (){
//var src = jQuery(this).attr("src").replace("thumbnail/66x66", "image");//changes src from thumbnail to large image
Needs the above but in prototype.
//jQuery('#image').attr("src", src);//updates large image
this.imageEl.writeAttribute("src","http://www.timelapseme.com/images/logonew.png");
val_scale = !this.showFull ? this.slider.value : 1;
this.scale(val_scale);
},
Try this:
updateImage: function (){
var src = $(this).readAttribute('src');
...
}
Thanks wajiw I fixed it by var that = this, so I could use it later and getting rid of .bind(this)
You're binding an event, so the click-handler should be:
...
updateImage: function(event)
{
var img = Event.findElement(event, 'IMG');
var src = img.src;
}
...

Categories

Resources