Random Images, Random Text show after Refreshing - javascript

I have these syntax to display random text and image after refreshing the browser. Everything works fine. Please take a look.
JavaScript
var quotes=new Array();
quotes[0] = "text1";
quotes[1] = "Text2";
quotes[2] = "text3";
quotes[3] = "text4";
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementsByTagName('img')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
HTML
<div id="quote"></div>
<div>
<img class="image" src="http://www.placehold.it/100x50&text=1" />
<img class="image" src="http://www.placehold.it/100x50&text=2" />
<img class="image" src="http://www.placehold.it/100x50&text=3" />
<img class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
CSS
.image {
display: none;
}
But later on, I add many more <img scr.../> tags (which are not related to the purpose of this JavaScript) on different places in the page, then the random images didn't show up.
I try a different way by changing document.getElementById to document.getElementByClassName as the syntax below, it doesn't work.
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementByClass('image')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
Then, I try to add an id="imgShow" in each <img..> tag
<div id="quote"></div>
<div>
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=1" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=2" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=3" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
And instead of document.getElementsByTagName, I change to document.getElementById as below, but the random images don't show, either.
Any idea?
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementById('imgShow')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
I also try to distinguish the random <img src> tags with other <img src> tags inside the page by adding an ID for the parent <div>, then trying to call only the <img> inside that ID, but no success.
HTML
<div id="quote"></div>
<div id="RefreshImg">
<img class="image" src="http://www.placehold.it/100x50&text=1" />
<img class="image" src="http://www.placehold.it/100x50&text=2" />
<img class="image" src="http://www.placehold.it/100x50&text=3" />
<img class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
JavaScript
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementById('RefreshImg img')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
Do you have any idea?

I'd go about it in a slightly different way.
HTML:
<div id='quote'></div>
<img id='quote-img'>
<!-- by giving the img tag an id, we can leave other img tags throughout
the document untouched when we set our random image -->
JavsScript:
var quotes = [
{img: "http://www.placehold.it/100x50&text=1", quote: "text1"},
{img: "http://www.placehold.it/100x50&text=2", quote: "text2"},
{img: "http://www.placehold.it/100x50&text=3", quote: "text3"},
{img: "http://www.placehold.it/100x50&text=4", quote: "text4"}
/*
I've moved the quotes and matching images into objects inside an array
That way, we keep stuff neatly together, and it allows for a great deal
of flexibility when it comes to adding or removing stuff.
*/
];
function showquote() {
var q = quotes.length;
// var whichquote=Math.round(Math.random()*(q-1)); // Logical error...
var whichquote=quote[Math.round(Math.random()*(q-1))]; // ... fixed.
/*
I've moved the quote selection logic into the showquote function.
Again, it allows for more flexibilty: now you could theoretically call
showquote multiple times (maybe through setTimeout for example) and
end up with a different random quote+image each time.
*/
document.getElementById('quote').innerHTML = whichquote.quote;
document.getElementById('quote-img').src = whichquote.img;
};
showquote();

Try something like this:
var quotes = [];
quotes[0] = "text1";
quotes[1] = "Text2";
quotes[2] = "text3";
quotes[3] = "text4";
var q = quotes.length;
var whichquote = Math.floor(Math.random()*q);
function showquote(){
document.getElementById('img'+whichquote).style.display = '';
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
<div id="quote"></div>
<div>
<img id="img0" style="display:none;" src="http://www.placehold.it/100x50&text=1" />
<img id="img1" style="display:none;" src="http://www.placehold.it/100x50&text=2" />
<img id="img2" style="display:none;" src="http://www.placehold.it/100x50&text=3" />
<img id="img3" style="display:none;" src="http://www.placehold.it/100x50&text=4" />
</div>

Related

jQuery append an img to every div

I am trying to display a thumbnail image with every thumb class, but currently I am getting the output below where the images are looping inside the href instead. The order of div, href and img must not change. It looks something like this jsfiddle but this isn't fully working of course...
currently getting:
<div class ='thumb'>
<a href="#" rel="1">
<img src="">
</a>
<img src="">
<img src="">
</div>
required output:
<div class ='thumb'>
<a href="#" rel="1">
<img src=>
</a>
</div>
<div class ='thumb'>
<a href="#" rel="1">
<img src="">
</a>
</div>
my loop:
var thumbnails = [];
$.each(data.productVariantImages,function(key, val){
thumbnails.push(val.imagePath);
});
for(var thumb in thumbnails) {
$('.thumb').append($('<img>').attr({
"src":[thumbnails[thumb]]
}));
}
am i looping it wrongly?
edit:
The thumbnails are part of a dynamic gallery where basically every time a user choose a different option in a dropdown list, the sources for the thumbs are supposed to change accordingly.
current html:
<div class="thumbnail"><?php
foreach($skuDetails['productVariantImages'] as $variantImage){
if(isset($variantImage) && $variantImage['visible']){
?>
<div class="thumb">
<a href="#" rel="1">
<img src="<?php echo $variantImage['imagePath']; ?>" id="thumb_<?php echo $variantImage['id']; ?>" alt="" />
</a>
</div> <?php }}?>
</div>
sample array of thumbnails:
["http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
"http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png"]
sample output:
<div class="thumbnail">
<div class="thumb">
<a href="#" rel="1">
<img src="http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples.png" id="thumb_323" alt="">
</a>
</div>
<div class="thumb">
<a href="#" rel="1">
<img src="http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples.png" id="thumb_323" alt="">
</a>
</div>
</div>
You need to use .each function on .thumb. Something like:
$(document).ready(function(){
$('.thumb').each(function(){
$(this).append($('<img>').attr({"src":[thumbnails[thumb]],}));
});
});
your loop is focused on wrong element. You append img tag to the thumb class. So, the img tags inside the same element. You should create div has thumb class inside the loop, and append it to the thumbnail div. That must like
var div = $(".thumbnail");
$.each(imageArray, function(index, value){
var elem = "<div class='thumb'><a href='#' rel='1'></div>";
div.append($elem);
$('.thumb').append("<img />").attr("src", value);
});
It may be wrong but you should watch the thumbnail element. I cannot write the code to test. But I think the logic must be like this.
If you want that exact structure, I made a demo using plain JavaScript. Enter a number and the thumbClone() function will generate that many. You could probably adapt this function with your existing code easily. I'm in rush, it probably needs refactoring, sorry. :-\
DEMO
function thumbClone(qty) {
var main = document.getElementById('main');
var aFig = document.createElement('figure');
var aLnk = document.createElement('a');
var aImg = document.createElement('img');
aLnk.appendChild(aImg);
aImg.src = "http://placehold.it/84x84/000/fff.png&text=THUMB"
aFig.appendChild(aLnk);
aLnk.setAttribute('rel', '1');
main.appendChild(aFig);
aFig.className = "thumb";
console.log('qty: ' + qty);
var thumb = document.querySelector('.thumb');
for (var i = 0; i < qty; i++) {
var clone = thumb.cloneNode(true);
thumb.parentNode.appendChild(clone);
}
}
You need to use each loop which will get each class rather than getting only one class below is syntax of each loop
$(selector).each(function(){
// do your stuff here
)};
in your case
$('.thumb a').each(function(){
// do your stuff here
$(this).append($('<img />').attr('src',[thumbnails[thumb]]);
)};
Looks like you need to create the entire div structure for each image.
Lets create the below structure dynamically using the max length of the image array and add the image src .
var thumbDivStart = "<div class ='thumb'><a href="#" rel="1">";
var thumbDivEnd = "</a></div>";
var thumbDiv = "";
for (i = 0; i < imageArray.length; i++) {
thumbDiv = thumbDivStart + "<img src="+imageArray[i]+"/>"+
thumbDivEnd;
//Here you can append the thumbDiv to the parent element wherever you need to add it.
}

How to make a list of id's or loop using multiple id's in Javascript?

I am trying to find out how to make a list of variables or preferably a loop that identifies the id's. Here is an example.
thumb1 = document.getElementById("image1");
But instead of it being "image1", I want it to go all the way up to image15.
I'd much rather have a loop with the code above that identifies the id's from "image1" to "image15". I am fairly new to Javascript so any help is appreciated! Thank you!
You could do something like this:
var elements = [];
for(var i = 1; i <= 15; i++) {
var id = "image" + i;
elements.push(document.getElementById(id));
}
But the smarter thing to do would be to just add a single class to all of your image elements and use it in combination with querySelectorAll:
var elements = document.querySelectorAll(".image");
<div>
<img id="image1" class="image" />
<img id="image2" class="image" />
<img id="image3" class="image" />
</div>

jQuery find closest

I'm trying to get the a href of an list item.
HTML
<div class="popup" style="display: none;">
<div class="product">
<div class="photo">
<a href="" class="sendkleur" id="link69"> <!-- href im trying to reach -->
<img id="product-collection-image-69" src="" alt="Test kleur" class="popup-image69">
</a>
</div>
<a href="" class="sendkleur" id="link69">
<strong>Test kleur</strong>
</a>
<span class="swatchLabel-category">Kleur:</span>
<p class="float-clearer"></p>
<div class="swatch-category-container" style="clear:both;" id="ul-attribute137-69">
<img onclick="listSwitcher();" src="" id="a137-32" class="swatch-category" alt="Beige" width="12px" height="12px" title="Beige">
<img onclick="listSwitcher();" src="" id="a137-36" class="swatch-category" alt="Zwart" width="12px" height="12px" title="Zwart">
</div>
<p class="float-clearer"></p>
</div>
</div>
There are multiple popups on the site and thats what makes it difficult. At first I used this code
var link = jQuery('.photo').find('a')[0].getAttribute("href");
But this ofcourse only returns the href of the first popup. Then I tried this code:
var link = jQuery('.photo').closest('a').attr("href");
But this returned undefined
Then I tried this:
var link = jQuery(this).closest('a').attr("href");
But that also returns undefined
Edit
Here is the whole jQuery code snippet
jQuery(document).ready(function(){
jQuery('.swatch-category-container img').click(function(){
var kleur = jQuery(this).attr('title');
var link = jQuery('.photo').find('a').attr("href");
console.log(link);
link += "?kleur="+kleur;
console.log(link);
jQuery('.photo').find('.sendkleur').attr("href", link);
});
});
Working from the .swatch-category-container img element, you can traverse the DOM to find the required a like this:
$('.swatch-category-container img').click(function() {
var link = $(this).closest('.popup').find('.photo a').prop('href');
// do something with link here...
});
If this is the .swatch-category-container img element then, the anchor is the previous to previous sibling of the ancestor swatch-category-container element
var link = jQuery(this).closest('.swatch-category-container').prev().prev().attr("href");
Since you said multiple popups, the idea would be like this.
1. Get all popups
2. From each popup in all popups
Get the photo href item
$('.popup').each(function() {
var hrefItem = $(this).find('.photo a').attr('href');
//Do your processing with href item
});

Linkmenu w/ MouseOver javascript

I have this menu made out of imagelinks on my website and want to have a different MouseOver function on every menuobject, i have tried like this but it always goes for the later script so when i hover start it changes to info.
<script language="javascript">
function MouseRollover(start) {
start.src = "starthover.png";
}
function MouseOut(start) {
start.src = "startidle.png";
}
</script>
<script language="javascript">
function MouseRollover(info) {
info.src = "infohover.png";
}
function MouseOut(info) {
info.src = "infoidle.png";
}
</script>
and for the links i got this:
<a href="test.html">
<img src="startidle.png" border="0px"
onMouseOver="MouseRollover(this)"
onMouseOut="MouseOut(this)" />
</a>
<a href="test.html">
<img src="infoidle.png" border="0px"
onMouseOver="MouseRollover(this)"
onMouseOut="MouseOut(this)" />
</a>
I wonder if there is any way to classify these functions so i can get the same function but different pictures for my menu?
Your 2nd script is overwriting the first one, which means every time you call "MouseRollover" or "MouseOut", your js will go for the 2nd script.
You can work with only one function that will swap you images, no need to have four functions.
<head>
<script>
function swapImg(element, img) {
element.src = img;
}
</script>
</head>
<body>
<a href="#">
<img src="startidle.png" border="0px" width="150px"
onMouseOver="swapImg(this, 'img01.jpg')"
onMouseOut="swapImg(this, 'img02.jpg')" />
</a>
<a href="#">
<img src="infoidle.png" border="0px" width="150px"
onMouseOver="swapImg(this, 'img03.jpg')"
onMouseOut="swapImg(this, 'img04.jpg')" />
</a>
</body>
Plus, it's "border" instead of "boarder".
You need only one function in your javascript.
Try it:
HTML
<a href="test.html">
<img src="startidle.png" boarder="0px"
onMouseOver="MouseRollover(this, 'starthover.png')"
onMouseOut="MouseOut(this, 'startidle.png')" /></a>
<a href="test.html">
<img src="infoidle.png" boarder="0px"
onMouseOver="MouseRollover(this, 'infohover.png')"
onMouseOut="MouseOut(this, 'infoidle.png')" /></a>
JAVASCRIPT
function MouseRollover(obj, image) {
obj.src = image;
}
function MouseOut(obj, image) {
obj.src = image;
}
Edit: You could use only one function
function changeImage(obj, image){
obj.src = image;
}

Using .next() and .replace() to view images that share similar classes

UPDATE: Here's a jsFiddle, so maybe you can see what I'm trying to accomplish here. I don't think I'm great at explaining myself. http://jsfiddle.net/dh4qx/
I have images in a slideshow I want to be able to view one-by-one using a next or previous button. I can't for the life of me figure out why this function isn't working, or how to make one that does work.
Here's the JS function I'm trying to call when div.next is clicked:
function resNextClick(){
var m = $('#slideshow2 img:visible').attr('class').replace(/\d+/, "");
var $curr = $('#slideshow2 img:visible');
var $next = $curr.next('img.' + m + '/\d+/');
$curr.fadeOut(200);
$next.fadeIn(200);
};
I'm trying to fade the visible image out, and bring up the next image which shares the same class minus the digit. Hope that makes sense.
Here's the HTML:
<div id="slideshow2">
<img class="oc1" src="/Users/justin/Desktop/res-links/oconner1.jpg" />
<img class="oc2" src="/Users/justin/Desktop/res-links/oconner2.jpg" />
<img class="oc3" src="/Users/justin/Desktop/res-links/oconner3.jpg" />
<img class="oc4" src="/Users/justin/Desktop/res-links/oconner4.jpg" />
<img class="el1" src="/Users/justin/Desktop/res-links/salinas1.jpg" />
<img class="el2" src="/Users/justin/Desktop/res-links/salinas2.jpg" />
<img class="el3" src="/Users/justin/Desktop/res-links/salinas3.jpg" />
<img class="el4" src="/Users/justin/Desktop/res-links/salinas4.jpg" />
<img class="el5" src="/Users/justin/Desktop/res-links/salinas5.jpg" />
<img class="el6" src="/Users/justin/Desktop/res-links/salinas6.jpg" />
<img class="el7" src="/Users/justin/Desktop/res-links/salinas7.jpg" />
<img class="el8" src="/Users/justin/Desktop/res-links/salinas8.jpg" />
<img class="ng1" src="/Users/justin/Desktop/res-links/nguyen1.jpg" />
<img class="ng2" src="/Users/justin/Desktop/res-links/nguyen2.jpg" />
<img class="ng3" src="/Users/justin/Desktop/res-links/nguyen3.jpg" />
<div class="img-close">x</div>
<div class="next">next</div>
<div class="prev">prev</div>
</div>
<div class="oc hide">
<div class="desc">
<h3>project: O'CONNER RESIDENCE</h3><br>
<h3>civil engineer: BAI</h3><br>
<h3>project location: CARMEL VALLEY, CALIFORNIA</h3><br>
<h3>dates of my involvement: 06/2006-01/2007</h3><br>
<h3>software: AUTODESK AUTOCAD 2007</h3><br>
<p>This project is typical of the residential projects that I was involved with at BAI. The client was architect IDG of Pacific Grove and BAI provided civil engineering services and project permitting. As drafter and designer, I designed the grading, drainage, erosion control, retaining walls, and underground utilities. The lead engineer approved my design and I then executed about half the drafting, with the balance drawn by others to my redmarks. Following submittal and initial plan check, I also wrote responses to comments from Monterey County Planning, the local fire protection and watershed management districts, the California Department of Water Resources, and the California Coastal Commission.</p><br>
<p>The civil planset as reproduced here was drawn in 09/2006 and submitted for permit in 01/2007.</p>
</div>
<div class="images">
<a href="#">
<div class="back">
BACK
</div>
</a>
<table>
<tr>
<td><img class="oc1" src="/Users/justin/Desktop/res-links/oconner1.jpg" /></td>
<td><img class="oc2" src="/Users/justin/Desktop/res-links/oconner2.jpg" /></td>
<td><img class="oc3" src="/Users/justin/Desktop/res-links/oconner3.jpg" /></td>
<td><img class="oc4" src="/Users/justin/Desktop/res-links/oconner4.jpg" /></td>
</tr>
</table>
</div>
As always, I appreciate all help and feedback.
You are passing RegEx to selector. That is not valid to do!
Try this:
function resNextClick(){
var m = $('#slideshow2 img:visible').attr('class').replace(/\d+/, "");
var $curr = $('#slideshow2 img:visible');
var $next = $curr.next('img[class^="' + m + '"]');
$curr.fadeOut(200);
$next.fadeIn(200);
};
You are doing it wrong, you should use a class for each group of related pictures
<div id="slideshow2">
<img class="oc" src="/Users/justin/Desktop/res-links/oconner1.jpg" />
<img class="oc" src="/Users/justin/Desktop/res-links/oconner2.jpg" />
<img class="oc" src="/Users/justin/Desktop/res-links/oconner3.jpg" />
<img class="oc" src="/Users/justin/Desktop/res-links/oconner4.jpg" />
<img class="el" src="/Users/justin/Desktop/res-links/salinas1.jpg" />
<img class="el" src="/Users/justin/Desktop/res-links/salinas2.jpg" />
<img class="ng" src="/Users/justin/Desktop/res-links/nguyen1.jpg" />
<img class="ng" src="/Users/justin/Desktop/res-links/nguyen2.jpg" />
</div>
And then something like this
function resNextClick(){
var $curr = $('#slideshow2 img:visible'),
cls = $curr.attr('class');
var $next = $curr.next();
// Toggle if next is the same class as this one
if ($next.attr('class') === cls) {
$curr.fadeOut(200);
$next.fadeIn(200);
}
}
You'll need to do an "attribute starts selector"
$curr.next($('*[class^="' + cls.trim() + '"]'))
That should give you the next item that has the same class prefix. I also trimmed the class string due to the extra space.
If the length of the final selector is zero, then you're at the end and should just get the first.
I made simple version of your slideshow (used code form ikaros45 answer as well)
You should be able to use it in your code and I hope it will help you.
Btw I am not sure is it correct way of doing it :)
HTML
<div class="img">
<div class="ox0">1</div>
<div class="ox1">2</div>
<div class="ox2">3</div>
<div class="ox3">4</div>
</div>
jQuery
$(".img div").click(function(){
var selected_img = $(this).attr( "class" ); //get class of clicked element
var group = selected_img.substring(0, selected_img.length - 1);
var set_img = $("#slideshow ."+group);
selected_img = selected_img.substring(2);
var showed = $('#slideshow img:visible');
showed.hide();
$(set_img[selected_img]).show();
$("#slideshow").slideDown();
/*
* for example you clicked on "ox1",
* var group - getting just text part of the class "ox"
* var selected_img - getting just number from class"1"
* var set_img - getting all elements in #slideshow with class "ox"
* $(set_img[selected_img]) - points which big img to open (ox[1])
*/
});
$("#img-next").click(function(){
var curr = $('#slideshow img:visible');
var cls = curr.attr("class")
var next = curr.next();
if (next.attr('class') === cls) {
curr.fadeOut(200);
next.fadeIn(200);
}
else{
var first_img = $("#slideshow ."+cls);
curr.fadeOut(200);
$(first_img[0]).fadeIn();
/*
* getting all elements with same class,
* and showing first
*/
}
});
http://jsfiddle.net/dh4qx/6/

Categories