Loading an image based on a variable - javascript

I've tried searching for several hours but cannot find an answer that works. I want to load a different image for each day of the year.
I have some js that creates a variable based on the date function. I concatenate this with other text strings to get this variable:
photo2load = http://www.example.com/photos/pic132.jpg
How do I then get this photo to load. What is the scripting required? I'm at a total loss.
Thanks in advance.

You need to add an id attribute to your image and then onload call a function with inside something like this:
function loadMyImage(){
var img = document.getElementById("id-of-image");
img.src = photo2Load;
}
Or if you want to pass directly your variable call the function like this
loadMyImage( photo2Load);
function loadMyImage(imgUrl){
var img = document.getElementById("id-of-image");
img.src = imgUrl ;
}

Related

How do i link all this images with an array

How do i link all this images to an array, so as this links can work when i click each image slide
jQuery(document).ready(function() {
var bgImageArray = ["banner1.jpg", "banner2.jpg", "banner3.jpg"],
var links = ['http://google.com', 'http://hotmail.com', 'http://yahoo.com', 'http://kimjoyfox.com'],
base = window.location.origin + "/wp-content/themes/fbnquest/img/home/",
secs = 4;
bgImageArray.forEach(function(img){
new Image().src = base + img;
// caches images, avoiding white flash between background replacements
});
The way I understand your problem is the following :
For each time you click on one of each of the images, you want to redirect the user to one of the URLs, changing the URL each time the user click on the image.
Is it what you want ? If not, please can you precise your problem
[EDIT]
So yes,
Here is my way of solving your problem, If you don't matter, I won't give you code, obviously, you do this for training, let's do it :
Create an eventListener on click that will trigger a function called ChangeImageUrl (for example) and assign that eventListener to all the img elements
Then create a function that will detect the current URL of the image clicked, using imgElement.src ( i advice you to devide the src string using split or equivalent, that way you can directly access by index the current url )
Once you have the URL Use yourUrlArray.indexOf(currentImageSrcUrl), to catch the index of the current URL in your array, store it and increment it ( bonus if the increment value is upper than the URL array length, set it to 0 )
access the new src using yourUrlArray[newindex]
assign current img element the new src that we juste have extracted
Tell me if this answer is good for you, I hope it will
I was trying to understand what do you really want and I did something that I hope help you.
Inside of the loop you can do in this way below.
var i = new Image();
i.src = base + img;

Turn a string into a variable name using window (JavaScript)

After scouring the forums, I've been trying to use window to turn a parameter entered as a string into a workable variable. Here we start with the target location in the p tag...
<p id="rent"></p>
Then I call the function using the parameter "rent" to obtain the variable rent.
var rent = 125;
function display(attribute) {
document.getElementById(attribute).innerHTML = window.attribute;
}
display("rent");
However it still returns "undefined" so I must be making a mistake in syntax. Any solutions?
Update: #Sidd has the right approach in changing it to window[attribute] but I still can't get it to work with object properties, for example if you call rent.amt.
You almost have it:
var rent = 125;
function display(attribute) {
document.getElementById(attribute).innerHTML = window[attribute];
}
display("rent");
window.attribute looks for a variable called attribute instead.

Referencing variables in an img src to make a link?

I'm trying to put a string and a number together so a variable is in an image link, and so the variable formed by the string and number's value would display in the link, but instead the raw name just displays, not the variable's value.
var link1 = 'restOfLink.gif';
var myFunction = function(number){
var imgLink = 'http://i60.tinypic.com/';
var randomNumber = Math.floor((Math.random()*5)+1);
$("div").append("<img src = '"+imgLink+'link'+randomNumber+"'/>");
}
randomNumber won't always be 1 but let's just assume it is.
The link shows up as http://i60.tinypic.com/link1.gif
Any help on that? I'm trying to make an app that displays a new random image when a div is clicked. (the code above isn't all of the code, but it's enough to cover my problem)
If you wanted to create a dynamic img element with a variable as the link or part of it you could do:
//These are just example variables, you can use your own the same way.
var imgPath = '/images/blog/';
var size = '200x450';
document.createElement('img').src = imgPath + 'yourImage' + size + '.png';
JsFiddle Demo.
For your example i would suggest creating an array of links that you can access using a random number, for example:
var links = ['restOfLink.gif', 'anotherexample.png', 'yetanother.jpg'];
To select a particular image from inside the links array you need to pass it the index it occurs at, with 0 being the first.
So for example:
links[0] --> "restOfLink.gif"
links[1] --> "anotherexample.png"
links[2] --> "yetanother.jpg"
See this JsFiddle demo using this method.
You should create the link string by concatenating the different parts in Javascript, and update the img src attribute afterwards. Something like:
var bar = 3;
var linkString = "http://www.foo.com/image_number_" + bar + ".jpg";
document.getElementById("yourImgId").src = linkString;
Best.
Dont know what you want. A JSFiddle would help as suggested but here is my try at a answer:
string = "lol";
number = 1;
source = string+number;
$(".element").attr('src', source+".jpg");
You need JQuery for this though.

Choose random image for every image Javascript

//Setting up the Array
var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://cdn.trendhunterstatic.com/thumbs/suit-animal-art-berkley-illustrations.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg'];
// creating the randomizing
var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
// image source looks for the attribute, by using the variable arraying
$('img').attr('src',random);
Above is my code. I currently have javascript set up this way. The current code has the piece where images are randomly replaced from an image from the array. I want to have the code state that switch every image with a new random image, not every image with the same time. I like how it is random every time, but I also want to random for each picture.
Set up a loop to go over each image, pick a random one, and then assign to that one:
var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://cdn.trendhunterstatic.com/thumbs/suit-animal-art-berkley-illustrations.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg'];
$("img").each(function() {
var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
$(this).attr('src',random);
});
You can use a callback function with the attr method to calculate the value for each element:
$('img').attr('src', function(){
return arrayImg[Math.floor(Math.random()*arrayImg.length)];
});

Trying to reduce repetition of javascript using a variable

I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.
The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.
I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.
E1 = new Audio('audio/E1.ogg');
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
fileName.play();
$('#note' + fileName).addClass('active');
});
The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.
How can I make this work? What am I missing?
Thanks.
fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).
Suggestion:
Store your objects in a table:
var files = {
E1: new Audio('audio/E1.ogg')
};
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
files[fileName].play();
$('#note' + fileName).addClass('active');
});
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5 data attributes:
<div id="#note" data-filename="E1">Something</div>
Then you can get the name with:
var filename = $('#note').data('filename');
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.

Categories