Change beginning of each image src with Javascript? - javascript

I am trying to use Javascript to change the beginning of each image src before the page loads.
I would want to change
src="v/image1.jpg"
src="v/image2.jpg"
src="v/image2.jpg"
to
src="http://different-server.com/v/image1.jpg"
src="http://different-server.com/v/image2.jpg"
src="http://different-server.com/v/image3.jpg"
Is there any way of doing that to all of the images of a certain class? Or would I have to create a loop that does this?
Thank you.

You may do like this:
var srcElement = document.getElementsByClassName('your_class');
for(var i=0;i<srcElement.length;i++){
srcElement[i].src = "http://different-server.com/" + srcElement[i].src
}

This code works :
$.each($("img"), function( index, value ) {
srcValue = "http://different-server.com/" + $(this).attr("src")
$(this).attr("src", srcValue)
});
See jsFiddle : http://jsfiddle.net/wkf3cpe9/

Related

javascript/html: Second onclick attribute

I have an image - image1.png. When I click a button the first time, I want it to change to image2.png. When I click the button for a second time, I want it to change to another image, image3.png.
So far I've got it to change to image2 perfectly, was easy enough. I'm just stuck finding a way to change it a second time.
HTML:
<img id="image" src="image1.png"/>
<button onclick=changeImage()>Click me!</button>
JavaScript:
function changeImage(){
document.getElementById("image").src="image2.png";
}
I'm aware I can change the image source with HTML within the button code, but I believe it'll be cleaner with a JS function. I'm open to all solutions though.
You'll need a counter to bump up the image number. Just set the maxCounter variable to the highest image number you plan to use.
Also, note that this code removes the inline HTML event handler, which is a very outdated way of hooking HTML up to JavaScript. It is not recommended because it actually creates a global wrapper function around your callback code and doesn't follow the W3C DOM Level 2 event handling standards. It also doesn't follow the "separation of concerns" methodology for web development. It's must better to use .addEventListener to hook up your DOM elements to events.
// Wait until the document is fully loaded...,
window.addEventListener("load", function(){
// Now, it's safe to scan the DOM for the elements needed
var b = document.getElementById("btnChange");
var i = document.getElementById("image");
var imgCounter = 2; // Initial value to start with
var maxCounter = 3; // Maximum value used
// Wire the button up to a click event handler:
b.addEventListener("click", function(){
// If we haven't reached the last image yet...
if(imgCounter <= maxCounter){
i.src = "image" + imgCounter + ".png";
console.log(i.src);
imgCounter++;
}
});
}); // End of window.addEventListener()
<img id="image" src="image1.png">
<button id="btnChange">Click me!</button>
For achieve your scenario we have to use of counter flag to assign a next image. so we can go throw it.
We can make it more simple
var cnt=1;
function changeImage(){
cnt++;
document.getElementById("image").src= = "image" + cnt + ".png";
}
try this
function changeImage(){
var img = document.getElementById("image");
img.src = img.src == 'image1.png' ? "image2.png" : "image3.png";
}
Just use an if statement to determine what the image's source currently is, like so:
function changeImage(){
var imageSource = document.getElementById("image").src;
if (imageSource == "image1.png"){
imageSource = "image2.png";
}
else if (imageSource == "image2.png"){
imageSource = "image3.png";
}
else {
imageSource = "image1.png";
}
}
This should make the image rotate between 3 different image files (image1.png, image2.png and image3.png). Bear in mind this will only work if you have a finite number of image files that you want to rotate through, otherwise you'd be better off using counters.
Hope this helps.
Check the below code if you make it as a cyclic:
JS
var imgArray = ["image1.png", "image2.png", "image3.png"];
function changeImage(){
var img = document.getElementById("image").src.split("/"),
src = img[img.length-1];
idx = imgArray.indexOf(src);
if(idx == imgArray.length - 1) {
idx = 0;
}
else{
idx++;
}
document.getElementById("image").src = imgArray[idx];
}
html
<button onclick=changeImage();>Click me!</button>
function changeImage(){
document.getElementById("image").attr("src","image2.png");
}

How can we make Image Carousel with background Image Property

I'm making an image carousel i'm bounded to use background-image property instead of using
<img src="Image">
tag. my carousel is working if I use img tag . But its not working when I use background-image property, how can I modify my code with background-image property.
see my fiddle :https://jsfiddle.net/korLasen/ and update it please thanks :)
or you can see code here
(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
function imageSliderSet(){
image.setAttribute('data-background', imageSet[index]);
index++;
if(index >= imageSet.length){
index = 0;
}
}
setInterval = (imageSliderSet, 2000);
})();
This is quite a strange question... however, I am not one to judge :)
Here is a jsfiddle based on your example. I ended up using jquery for this. I hope this is somewhere near what you were looking for!
This is based on changing every two seconds. To extend that, you can change line 18 in the jquery. Here is the jquery:
$( document ).ready(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
window.setInterval(function(){
image.css('background-image', "url('" + imageSet[index] + "')");
index++;
if(index >= imageSet.length){
index = 0;
}
//here you can adjust the time interval for each photo
}, 2000);
});

Dynamically replace img src attribute with jQuery

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);

Get image src with jQuery

<img src="../img/arnold.png" alt="Arnold">
How do I get with jQuery absolute path of this image?
img.attr("src") gives me just "../img/arnold.png", should give something like "http://site.com/data/2011/img/arnold.png" (full url).
alert( $('img')[0].src );
this might do the trick... but not sure about cross browser....
demo in here
also try prop of jQuery 1.6..
alert( $('img').prop('src') );
demo here
I don't know that you can get it with jQuery, but you can get it with just the native JavaScript image object.
var getSrc = function(imgSource) {
var img = new Image();
img.src = imgSource;
return img.src;
};
Just call it with x = getSrc(srcAttribute) or something similar where your parameter is the string or literal holding the src you currently have in your html/image. It will return something like http://your/site/path/to/image.jpg
http://jsfiddle.net/BradleyStaples/cQMjQ/
Give current clicked image source in jQuery
jQuery(document).ready(function($){
$('body').on('click','img',function(){
alert('it works');
var imgsrc=$(this).attr('src');
alert(imgsrc);
});
});

Dynamically changing images in a div

I've five images and would like to display it in a same div one by one with interval of 2 sec. Can anyone please suggest any solution for this?
Simple javascript example:
var currentImage = 0;
var images = [
'a.jpg',
'b.jpg'
];
var imageElement = document.getElementById('yourImageTagId');
function nextImage(){
currentImage = (currentImage + 1) % images.length;
imageElement.src = images[currentImage];
}
var timeoutId = setTimeout(nextImage, 1000);
It expects you to have some html like this:
<img src="a.jpg" id="yourImageTagId" />
Jquery Cycle is really flexible... you could hook it up to whatever youve got already marked up pretty easily.
There are many ways to do this nowadays but one simple way is using the following jquery plugin:
http://jquery.malsup.com/cycle/
Here is a simple demo in action fading images one after the other.
http://jquery.malsup.com/cycle/basic.html
setTimeout
You can do something like this.
function selectData(currentIndex) {
// select current's element "display" to "none" and show next element
...
// schedule next change in two second
setTimeout("selectData(" + nextIndex + ");", 2000);
};
I assume all images are inside that div already and have style display:none

Categories