Dynamically pass random javascript array value to html img src - javascript

I'd like to dynamically pass an array value (in this case, String "../name1.jpg" or "../name2.jpg") to the img src <img src="here">. Each time you hover over "Class of 2013", a random image will fade in, then fade out.
Is that possible to pass in a value by calling it as such? <img src="getImages(); ?
How would you do it?
var ImgArray = new Array();
ImgArray[0] = "../name1.jpg";
ImgArray[1] = "../name2.jpg";
$(document).ready(function() {
show();
});
function show(){
$(".box").hover(
function(){ $(this).find(".overlay").fadeIn(); } ,
function(){ $(this).find(".overlay").fadeOut(); }
);
}
function getImages() {
int i = Math.random() * (max - min) + min;
return ImgArray[i];
}
HTML:
<div class="box">
Class of 2013:
<div class="overlay"> <!-- Put images to display here...-->
<img src="getImages();" alt="image to be displayed" />
</div>
</div>​
Thank you
EDIT: Current Code:
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
var ITLP = new Array();
ITLP[0] = "/corp/itlp/ITLP%20Bios/DanTurcotte.jpg";
ITLP[1] = "/corp/itlp/ITLP%20Bios/gomezwilmann.jpg";
$(document).ready(function() {
showimg();
});
function showimg()
{
$(".box > .overlay > img").attr("src",getImages());
$(".box").hover(
function(){ $(this).find(".overlay").fadeIn(); } ,
function(){ $(this).find(".overlay").fadeOut(); }
);
}
function getImages() {
int i = Math.abs(Math.random());
return ITLP[0];
}
</script>
</head>
<body>
<div class="box">
Class of 2013:
<div class="overlay"> <!-- Put images to display here...-->
<img src="" border="none"/>
</div>
</div>​
</body>
</html>

I prefer the classic way:
$(".box > .overlay > img").attr("src",getImages());
Extension:
function show()
{
$(".box > .overlay > img").attr("src",getImages());
$(".box").hover(
function(){ $(this).find(".overlay").fadeIn(); } ,
function(){ $(this).find(".overlay").fadeOut(); }
);
}
I think your requested way doesn't work, because the browser expect a string for the source attribute.
P.S.: Take an eye on your random function. My Firefox did complain something "(missing ';' before statement")

You may try this
var ImgArray = new Array();
// add images
$(document).ready(show);
// Show function
function show(){
$('img').attr('src', ImgArray[0]).parent().hide();
var max = ImgArray.length;
$(".box").hover(
function(){ $(this).find(".overlay").fadeIn(); },
function(){
var img = $(this).find(".overlay").find('img');
var i = Math.floor(Math.random()*max);
$(this).find(".overlay").fadeOut(function(){
img.attr('src', ImgArray[i]);
});
}
);
}
DEMO.

You want to change the source of the image in your first hover function (the one with fadeIn).
Since you're already using jQuery, just do this:
function(){ $(this img).attr("src", getImages()); $(this).find(".overlay").fadeIn(); } ,
and set your img's src initially to "". Of course, you could simplify your jQuery if you added an id to the img tag.
EDIT
I set up a fiddle with a working example here.
This is the script code:
var ITLP = [];
ITLP[0] = "http://lorempixel.com/400/200/nature";
ITLP[1] = "http://lorempixel.com/400/200/city";
function getImages() {
var i = Math.floor(Math.random() * (ITLP.length + 1)); // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FMath%2Frandom
console.log(ITLP[0]);
return ITLP[0];
}
function showimg() {
$(".box").hover(
function () {
console.log("Hover start");
$(".box > .overlay > img").attr("src", getImages());
$(this).find(".overlay").fadeIn();
},
function () {
console.log("Hover end");
$(this).find(".overlay").fadeOut();
});
}
showimg();
Major things I did:
Ordered the functions to be declared before they're used.
Got rid of the int i declaration that was killing getImages()
To get it this far, I used the console log a lot, and also jsfiddle's JSHint is a big help.

Related

variable inside getelementbyid in javascript not working

I want to reuse an image swap function on multiple divs, but the function is not acknowledging the adbox variable on the var rotator = getelementbyid(adbox).
window.onload = animatez(animate);
the animatez function should pass "animate" which is the div id to getelementbyid inside the function.
function animatez(adbox) {
var adbox;
var rotator = document.getElementById(adbox);
var images = rotator.getElementsByTagName("img");
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none"; }
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;}
}, 1000);
};
window.onload = animatez(animate);
<style>
#animate { width:200px; height:200px; background-color:transparent;
margin:auto; position:absolute;
}
img {width:200px; height:200px; display:none;}
</style>
<body>
<div id="animate">
<img src="surveyfunny.png">
<img src="myanswertoasurveyquestion.png">
<img src="funny-wheredoyoulive.png">
<img src="funnysurveyquestion2.png">
<img src="funnysurveyquestion.png">
</div>
You need give the function a string parameter. Without quote the animate is undefined, javascript throw the error.
see https://jsfiddle.net/pconline2046/u5cbwpuL/3/#
window.onload = function(){
animatez('animate');
};
window.onload needs to be set equal to a function, not the result of calling your animatez function. You could do something like this.
window.onload = function(){
animatez('animate');
};
Also notice that you need to pass a string to your animatez function so I have quoted animate.
Edit: Like some other answers have stated you also should remove the
var adbox;
line in your function.
Why do you have adbox var defined twice? Once at function animatez(adbox) { and again at var adbox...?

Switch content of DIV with another set DIVs with a timer

I have 3 divs in a html page, 2 divs should be hiddent always but theire content should be displayed in another div and this content should be changed every x seconds. Hows that possible using jquery/javascript?
<div id="contentA">
<!-- Some contents goes here, and it should be hidden -->
</div>
<div id="contentB">
<!-- Some contents goes here, and it should be hidden -->
</div>
<div id="displayArea">
<!-- switch between contentA and contentB on a timer say every 5 seconds -->
</div>
Do not use the .html() function to copy content from one place to another. HTML is a serialisation format designed to carry DOM structures from a server to a client. Once the page is in a DOM structure you should manipulate that DOM structure directly using DOM methods. Using .html() to serialise a DOM node and then recreate it somewhere else risks losing things like event handlers, other hidden data, etc.
On that basis, to copy the current contents of a div into another:
var $contents = $('#contentA').contents().clone(); // copy the source element's contents
$('#displayArea').empty().append($contents); // drop them into the destination
In full:
(function() {
var delay = 3000;
var state = 0;
(function next() {
state = 1 - state;
var src = state ? '#contentA' : '#contentB';
var $contents = $(src).contents().clone();
$('#displayArea').empty().append($contents);
setTimeout(next, delay);
})();
})();
Try this :)
<div id='a' style='display: none;'>this is a</div>
<div id='b' style='display: none;'>this is b</div>
<div id='show'></div>
<script>
$(document).ready(function(){
var count = 0;
var content = '';
var j = setInterval(function () {
count++;
if(count%2===0){
content = $('#a').html();
}else{
content = $('#b').html();
}
$('#show').html(content);
}, 5000);
});
</script>
Try this:
var toggle = false;
$("#displayArea").html($("#contentA").html());
setInterval(function() {
$("#displayArea").html(toggle ? $("#contentA").html() : $("#contentB").html());
toggle = !toggle;
}, 5000);
Working DEMO
I don't know if this is what you need but this script should work:
check = true;
$(document).ready(function(){
setInterval(function(){
if(check) {
check = false;
$('#displayArea').html("a");
}
else {
check = true
$('#displayArea').html("b");
}
}, 5000);
});
function doSlides() {
var msg = messages.shift();
messages.push(msg);
$('#displayArea').html(msg);
};
var messages = [
$('#contentA').find('p').html(),
$('#contentB').find('p').html()
];
Demo:
http://jsfiddle.net/8Ux3L/
Here's one way to do it using setInterval():
var divs = $('div[id^="content"]').hide(),
i = 0;
function cycle() {
$("#displayArea").html(divs.eq(i).html());
i = ++i % divs.length; // increment i, and reset to 0 when it equals divs.length
}
setInterval(cycle, 2000); //Cycle every 2 seconds
Wrapping in a self executing function:
(function cycle() {
$("#displayArea").html(divs.eq(i).html());
i = ++i % divs.length; // increment i, and reset to 0 when it equals divs.length
setTimeout(cycle, 2000);
})();
DEMO
Try following code
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script>
var divSelected = "A";
function switch1()
{
if (divSelected == "A")
{
$("#displayArea").text($("#contentA").text());
divSelected = "B";
}
else
{
$("#displayArea").text($("#contentB").text());
divSelected = "A";
}
}
$(document).ready(function()
{
var test = setInterval( "switch1()" , 5000);
});
</script>
</head>
<body>
<div id="contentA" style = "display:none;">
Contect A
</div>
<div id="contentB" style = "display:none;">
Content B
</div>
<div id="displayArea">
</div>
</body>
</html>
Use an interval to trigger a function every x seconds, then jQuery replaceWith to swap the divs. If you don't want to replace the actual node but just the contents, then .html() is probably the way to go.

How do I exchange two images in a webpage (on two consecutive clicks) using jQuery?

I have two images among many that I want to swap places between. If I click on one image, then the other, the respective images should swap with each other and the rest should remain the same. I'm a beginner at this so any help or direction would be helpful.
This works also for every image:
<img src="http://stunningwebsitetemplates.files.wordpress.com/2011/12/jquery.png"/>
<img src="http://bloggerschmidt.de/images/stories/logo-mootools.gif" />
<img src="http://stunningwebsitetemplates.files.wordpress.com/2011/12/jquery.png"/>
<img src="http://bloggerschmidt.de/images/stories/logo-mootools.gif" />
JS
$(function(){
var src="";
var old;
$("img").click(function(){
if(src=="")
{
src=$(this).attr("src");
old=$(this);
}
else
{
old.attr("src",$(this).attr("src"));
$(this).attr("src",src);
src="";
}
});
});​
Another solution without any global variable.
html
<div id="images">
<img scr="/images/1.jpg" />
<img scr="/images/2.jpg" />
<img scr="/images/3.jpg" />
<img scr="/images/4.jpg" />
<img scr="/images/5.jpg" />
</div>
Js file
$('img').click(function(){
if($('#images img').hasClass('selected')){
var src = $(this).attr('src');
$('.selected').attr('src',src);
$(this).attr('src',$('.selected').attr('src'));
$(this).removeClass('selected');
}
else
$(this).addClass('selected');
});
Here is a different approach that swaps the actual elements rather than the src of the img, also avoids using external variables for the swap.
$('img.swap').on('click', function() {
var t = $(this);
if (t.hasClass('clicked')) {
t.removeClass('clicked');
return;
}
var clicked = $('img.swap.clicked')
if (clicked.length === 0) {
t.addClass('clicked');
return;
}
var placeHolder = $('<div id="placeholder"></div>');
clicked.before(placeHolder);
t.after(clicked);
placeHolder.before(t).remove();
clicked.removeClass('clicked');
});​
Example - http://jsfiddle.net/BxST9/3/ (using div instead of img but shouldn't make a difference)
See the example on: http://jsfiddle.net/Lvp4j/1/
var selected;
$("img").click(
function() {
if (!selected)
{
selected = this;
$(selected).addClass("selected");
}
else
{
var src1 = $(selected).attr("src");
var src2 = $(this).attr("src");
$(this).attr("src", src1);
$(selected).attr("src", src2);
$(selected).removeClass("selected");
selected = null;
}
}
);
My code adds also a selected class so you can highlight the clicked image...
try below code
html
<div>
<img scr="/images/1.jpg" />
<img scr="/images/2.jpg" />
<img scr="/images/3.jpg" />
<img scr="/images/4.jpg" />
<img scr="/images/5.jpg" />
</div>
Js file
(function() {
var swapArray = [];
var count=0;
$('img').click(function(){
count++;
swapArray.push($(this).attr('src'));
$(this).addClass(count);
if(count==2){
$('.1').attr('src',swapArray[1]).removeClass('1');
$('.2').attr('src',swapArray[0]).removeClass('2');
swapArray.length = 0;
count=0;
}
});
}());​
Given this HTML:
<img src="image_1.jpg" />
<img src="image_2.jpg" />
<img src="image_3.jpg" />
<img src="image_4.jpg" />
You could use the following JavaScript:
(function() {
var previous = null;
$('img').click(function() {
var current = $(this);
if (current.is(previous)) { // clicked same image twice; reset
reset_clicked();
} else if (previous != null) { // two images clicked; swap
swap_src(previous, current);
reset_clicked();
} else {
set_clicked(current);
}
});
function reset_clicked() {
previous.removeClass('clicked');
previous = null;
}
function set_clicked(img) {
img.addClass('clicked');
previous = img;
}
function swap_src(img1, img2) {
var src1 = img1.attr('src');
img1.attr('src', img2.attr('src'));
img2.attr('src', src1);
}
}());​
The 'clicked' class is added purely so you can use CSS to style clicked images. This class could also be used to identify any previously-clicked images, but I've used a JavaScript variable instead because that's quicker than a DOM lookup.
There's a demo on JSFiddle: jsfiddle.net/cvthL/2
This answer was posted as an improved version of Jitendra Pancholi's first answer and an alternative to his/her second answer.

Image-loaded-show function by javascript in mobile browser

I'am using the following javascript code to implement image-loaded-show function in mobile web browser (supporting HTML5). Image-loaded-show means that before the image is completely loaded, the width and height is 0, namely it willn't show and occupy any space.
Now the problem is that the images will not show until all the images are loaded.
What I need is that the iamge in the page is seperate, once loaded, the image show up.
Any tips on how to modify this javascript code? thanks.
<script type='text/javascript'>
var srcs = [];
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
}
var content = document.getElementById('content');
var images = content.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
srcs[i] = images[i].src;
loadImage(images[i], srcs[i],
function (cur, img, cached) {
cur.src = img.src;},
function (cur, img) {
cur.style.display = 'none';});
}
};
var loadImage = function (cur, url, callback, onerror) {
var img = new Image();
img.src = url;
img.width = '100%';
if (img.complete) {
callback && callback(cur, img, true);
return;
}
img.onload = function () {
callback && callback(cur, img, true);
return;
};
if (typeof onerror == 'function') {
img.onerror = function () {
onerror && onerror(cur, img);
}
}
};
</script>
The source code of the page is :
<body onload="doBindLinks();"><div id="content"> images and text </div></body>
P.S: Because I need to write this javascript string in C#, I replace the (") into (').
Edited:
Is the following right:
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
elem.setAttribute('display','none');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
elem.attachEvent('onload',onImageLoaded);
}
};
window.onImageLoaded = function() {
var elem = event.srcElement;
if ( elem != null ) {
elem.setAttribute('display','block');
}
return false;
};
Besides, the css code is:
img {width: 100%; border-style:none;text-align:center;}
But the images still wouldn't show until all are loaded.
I'm not 100% sure I understand your question. Are you trying to hide the image until it is fully loaded? Are you writing the images out to the page, or are they already in the page? Here are a couple of options:
set style="display:none". Then add onload="this.style.display='';" event listener to image.
images will each show as they are loaded.
if you are able to change the c# code, then simply write all the image urls out as a list of strings into an imageload function. Then use this function to create the images and add them to the content div.
I hope this helps you. If not, please provide more context, and I will try to help farther.
Ok, I see where you are going now. You can take out all that javascript that you have written. Maybe print it out so that you can throw it in the trash. Then take my example here... and it will do the trick for you. each image shown only as it is loaded. Obviously if you want to change any other properties you can do it in the showImage function. hope this helps.
<html>
<head>
<style>
img{display:none;}
</style>
<script type="text/javascript">
function showImage(elem) {
elem.style.display = 'block';
}
</script>
</head>
<body><div id="content">
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
</dvi>
</body>
</html>

Toggling between two images by clicking

Due to this link
I changed it to this one:
<html>
<head>
<script>
var toggleimage=new Array("p1.gif","p.gif")
//do not edit the variables below
var image_1=new Image()
var image_2=new Image()
image_1.src=toggleimage[0]
image_2.src=toggleimage[1]
var i_image=0
function testloading() {
isloaded=true
}
function toggle() {
if (isloaded) {
document.togglepicture.src=toggleimage[i_image]
}
i_image++
if (i_image>1) {i_image=0}
}
onload=testloading
</script>
<title>
</title>
<meta content="">
<style></style>
</head>
<body>
<img name="togglepicture" src="p1.gif" border="0">
</body>
</html>
when I click on the image p it will show me p1 and vice versa
Now I have problem image has a name:
<img name="togglepicture" src="p1.gif" border="0">
and it will get the name here:
document.togglepicture.src=toggleimage[i_image]
I want to have many images so I thaught I need to change the togglepicture to a variable
for example:
function toggle(a) {
if (isloaded) {
document.a.src=toggleimage[i_image]
}
i_image++
if (i_image>1) {i_image=0}
}
and for input forexample it will be toggle('nameofimage') and in the href it will be something like
<a href="javascript:toggle('pic1')">
I wasn't successful.How can I use this function when I have more than a picture to click?
I made a modular toogle, visible here: http://jsfiddle.net/Regisc/N7bgz/2/
Usage sample:
<img id="image1" src="http://dummyimage.com/50/f00/fff&text=a"
onclick='toogle(this, ["http://dummyimage.com/50/ab0/fff&text=b",
"http://dummyimage.com/50/ab0/fff&text=c"]);' />
you can't use
document.a.src=toggleimage[i_image];
instead use
document.getElementById(a).src=toggleimage[i_image];
And you also need to add an id to your img element.
Something like the following should work for any number of images provided toggleimage is a contiguous array.
var toggleimage = ["p1.gif","p.gif"];
var toggle = (function() {
var count = 0;
var len = toggleimage.length;
var el = document.getElementsByName('togglepicture')[0]
return function() {
if (isloaded) {
el.src = toggleimage[count++ % len];
}
};
}());
I'm not entirely sure I got your question. Are you asking:
How to edit the function to allow toggling between more than just two images, or
How to edit the function to handle more than one set of toggle images?
Toggling between more than just two images
var toggleimage=new Array("p1.gif","p.gif","p2.gif","p3.gif","p4.gif")
var totalImages=4;
function toggle() {
if (isloaded) {
document.togglepicture.src=toggleimage[i_image]
}
i_image++
if (i_image>totalImages) {i_image=0}
}
How to edit the function to handle more than one set of toggle images?
call the JS function like this
<a href="javascript:toggle(this)">
And, in your JS function,
var id = div.id;
Use this in an if-else to determine which control called the function and accordingly which array of images to use.
function toggle(div)
{
var id = div.id;
if (isloaded)
{
if (id == 'myFirstToggleImageControl')
{
document.togglepicture.src=toggleimage[i_image];
}
else if (id == 'mySecondToggleImageControl')
{
document.togglepicture.src=toggleimageSource2[i_image];
}
}
i_image++
if (i_image>1) {i_image=0}
}
Note: You will want to use an independent counter for the second control. So, possibly i_image1 and i_image2
<html>
<head>
<script>
// images list (properties name must by equal to id of IMAGE html element)
var imageList={
image1: {
currentIndex:0,
images:["p1.gif","p.gif"]
}
};
// preloading images using closure (additionaly replace image URL's with image objects)
(function() {
for(var p in imageList)if(imageList.hasOwnProperty(p)) {
for(var i=0;i<imageList[p].images.length;i++) {
var img=new Image(),src=imageList[p].images[i];
(imageList[p].images[i]=img).src=src;
}
}
})();
function toogleImage() {
var info=imageList[this.id];
info.currentIndex++;
if(info.currentIndex===info.images.length)info.currentIndex=0;
this.src=info.images[info.currentIndex].src;
}
// setting start images
window.onload=function() {
for(var p in imageList)if(imageList.hasOwnProperty(p)) {
//try{
document.getElementById(p).src=imageList[p].images[0].src;
//}
//catch(ex){}
}
}
</script>
</head>
<body>
<img id="image1" onclick="toogleImage.call(this);"/>
</body>
</html>
http://jsfiddle.net/X4Q2m/

Categories

Resources