Keep getting same value from jQuery array - javascript

I have two problems.
I have a jQuery array which stores the URL's for images. Everything was working fine a few minutes ago, but now it's not. I have the following code for the images:
var images = ["link1","link2","etc","etc"];
index=0;
this to display them when you click their thumbnails:
$('.thumbnail').click(function(){
$('.large_view').prepend('<img src="'+images[index]+'" width="450px"/>');
});
and this to show the previous/next images in the array:
$('.next').click(function(){
index = (index===0)?(images.length-1):(index-1);
$('.large_view img').attr('src',images[index]);
});
$('.previous').click(function(){
index = (index==images.length-1)?0:(index+1);
$('.large_view img').attr('src',images[index]);
});
My problem is that when I click a thumbnail, the same image (the first one in the array) always shows up. After that I can change the image properly with my next/previous buttons.
When I display the images in my array with code that includes the following, it shows up backwards, from the last item in the array to the first one: for(var i=0; i<images.length; i++)
P.S. the only reason the code inside .previous and .next are backwards is because the array is somehow backwards, like I said.

The first problem is that when any thumbnail is clicked, index will be at its original value of 0, which is what's always making the first one show up. To fix this, you'll need to determine the corresponding index from whichever thumbnail was clicked (perhaps using $(this).attr('data-image-index'), if you stuffed the index into an attribute like that).
The second problem is that you want to use .append instead of .prepend in the for loop to tack each new thumbnail onto the end of the set instead of the beginning.
Also, the click handlers for .next and .previous appear to be backwards.
And you might want to use $('.large_view').html(...) instead of $('.large_view').prepend(...) if you only want one large picture to be displayed at any given time.

1) your index is 0, so you are going to get the first image every time.
this line
$('.large_view').prepend('<img src="'+images[index]+'" width="450px"/>');
should be changed, to reference the index of the clicked thumbnail instead of the variable called index. so something like
$('.large_view').prepend('<img src="'+ $(this).attr("index") +'" width="450px"/>');
You will add the index attr when creating the thumbnails, for example:
for( var i=0; i<images.length; i++){
var thumbnails = '<label class="align">' + '<img class="thumbnail" src="'+images[i]+'" index="' + i + '"/></label>';
$('.gallery').prepend(thumbnails);
}
2) for your second problem, you are using prepend, which as the name implies PREpends. you will want to use append() to get them in the forward sequence as you want.

Related

Load dynamic content in Owl Carousel 2

I have a webpage with 2 carousels in which I have to show different items depending on user actions.
The new data comes from the internet, I use fetch, parse the json into an array, all good.
Only problem is I can't have the new items replace the old ones in the carousel.
For a simple example I have tried
var carousel = $jq("#owl-genres");
for(...) {
carousel.owlCarousel()
.trigger('add.owl.carousel', [$jq('<div class="item">' + genres[i] + '</div>')])
.trigger('refresh.owl.carousel');
}
but nothing happens. The old elements remains, although the methods executes and the .trigger is executed.
I have also tried
for(...) {
content += '<div class=\'item\'>' + genres[i] + '</div>'
carousel.html(content)
}
carousel.owlCarousel().trigger('refresh.owl.carousel');
which indeed adds the new items to the carousel but they are now vertically stacked, the navigation doesn't work, I guess the whole carousel is broken.
So what's the correct way to replace the items in Owl Carousel 2?
Solution based on https://stackoverflow.com/a/37862372/4249825
This can all be put in a function which receives the new array of elements to display and be executed as soon as we fetch new data.
Hope it will help others (I saw there are many questions about this...)
//these 3 lines kill the owl, and returns the markup to the initial state
carousel.trigger('destroy.owl.carousel');
carousel.find('.owl-stage-outer').children().unwrap();
carousel.removeClass("owl-center owl-loaded owl-text-select-on");
// add the new items
for (var i = 0; i < genres.length; i++) {
content += "<div class=\"item\">" + genres[i] + "</div>"
}
carousel.html(content);
//reinitialize the carousel (call here your method in which you've set specific carousel properties)
carousel.owlCarousel();
I found the issue was supplying an array to trigger('add.owl.carousel', array) and everything worked when I joined the array e.g. trigger('add.owl.carousel', array.join('')).

How to determine the img source using Jquery/Javascript on pageload?

I've gone through many SO threads, I can't seem to find a working solution.
All I'm trying to do is when the page loads, the site pushes all elements with the ".home" class into the array arr. Then, the script parses through each element in the array and tries to match it with a string. For example, right now all I have is a check to see if the element has the words "Boston" in it, in which case I want to make the image source for ".homeimage" the linked imgur link. I'm aware it's not wise to host images on imgur for these reasons, I'm just trying to check if it works. Below this test I have some redundant code I was practicing with that I found in a SO thread, changing the color of text to gray. I figured changing attributes is the same.
my html code:
<td colspan = "3"width=400px class = "home"><b><%= game.home %></b></td>
<td colspan = "3"><img style="width:150px;height:128px;" class = "homeimage"></td>
my javascript/jquery code:
<script>
var arr=[];
$(document).ready( function(){
$(".home").each(function(){ arr.push($(this));});
for(i = 0; i < arr.length; i++){
if(arr[i].indexOf "Boston" != -1){
$('.homeimage img').attr("src","http://i.imgur.com/s5WKBjy.png");
}
}
$.each(arr,function(key,val){
val.css('color','gray')}); //something redundant i was testing out
});
</script>
additional questions:
When I have multiple image with the .homeimage class, and multiple checks to determine the image source, will it make all of the images in the .homeimage class that src at the end? So whatever the last image that gets checked is the image src for all of the images with the ".homeimage" class? I don't want that. How can I uniquely make each image? Make a custom id instead of a class for each div? Also, does this script have to be below the html in question? Or does that not matter
Thanks for the future advice you all.
// I don't quite understand what you want to do.
// Since you type too much, and make no highlights.
// but here are somethings I found:
var arr = []; // this array is going to contain all tags (like td) with class '.home'
if(arr[i].innerHTML.indexOf("Boston") != -1) { } // indexOf() won't work on DOM element
// then arr[0] must be a DOM element, so why you call .indexOf("Boston") on it?
// next, $('.homeimage img') all return DOM element with class 'homeimage' or with tagName 'img'
$('img.homeimage'); // this may what you want to do.
// Alright, I try to give you an answer.
// this oImgUrl works as a map from some ((String))-->((img url))
var oImgUrl = {
'Boston': 'http://another.imageurl.com/boston.png',
'NewYork': 'http://another.imageurl.com/newyork.png'
};
// I take your "arr" unchanged
// this will test every element in arr
// if carry String like 'Boston' or 'NewYork'
// then find the img tag (img.homeimage) in it.
// then apply URL string to img tag
for (var i=0, length=arr.length; i < length; i++) {
if(arr[i].innerHTML.indexOf("Boston") != -1) {
arr[i].find('img.homeimage').attr('src', oImgUrl['Boston']);
continue;
}
if(arr[i].innerHTML.indexOf("New York") != -1) {
arr[i].find('img.homeimage').attr('src', oImgUrl['NewYork']);
continue;
}
}
example html:
<td class='home'>Welcome to Boston!<img class='homeimage'></td>
<td class='home'>Welcome to New York!<img class='homeimage'></td>
answers:
Question 1: Custom ID?
JavaScript will find these two td.home and add them into arr.
then, apply different image url to img tag
according to innerHTML of the td tag.
when doing this, you don't need to set each img tag an unique ID.
Question 2: Script place below html?
No, you don't have to.
You hold all thses script in docuement ready function
so, they will only work when HTML DOM is ready.
in another words, no matter where you place this script,
they will be invoked after Every Tag is ready.

Javascript adding and removing values from an array which are called outside the array

I am adding a bunch of spans to a div layer with appendchild like so:
var newSent = document.createElement("SPAN");
var current = document.createTextNode(sentInput.value);
newSent.style.backgroundColor = sentColor;
newSent.className = "sentSpan";
newSent.id = count - 1;
newSent.appendChild(current);
outputBox.appendChild(newSent);
Where outputBox is the name of the div layer and sentInput is the current value of an input text box. I need each of these spans to be click-able, and then delete their value from an array. Currently I have an event listener for this:
delCount = 0;
newSent.addEventListener("click", function(){
var x = parseInt(newSent.id);
sentCount.splice(x - delCount, 1);
sentNum.splice(x - delCount, 1);
delCount = delCount + 1;
newSent.remove(x);
});
The idea is that every time I delete a span, the delCount goes up to compensate for the now smaller array.
This doesn't work very well after a couple of deletions... I don't seem to be able to figure out the math or the proper method for handling the changing array. After clicking two or three spans I end up deleting the value in the array that was associated with the span next to it, but successfully removing the span itself. This array is displayed on a graph, so it's vital that it's displayed properly.
I temporarily had the arrays replace the deleted values with "0" which worked very well, but I need them to not show up in the array at all. Any help is greatly appreciated!
EDIT: added a jsfiddle http://jsfiddle.net/eL11o6mu/ though the display looks terrible in a window that small...

jQuery change picture of store item

I am building a website with a store interface and I have multiple store items with 2 small pictures and a big picture. I want to be able to mouseover the smaller picture and change the source of the big picture to the same source as the currently moused over small picture.
<div id='store_checkout_image_div'>
<img default-image='Images/test-shirt.jpg' src='Images/test-shirt.jpg' alt='Shirt' class='store_checkout_image'/>
<div id='small_images'>
<img id='store_image_1' src='Images/placeholder1.jpg' alt='Front' class='fade_store'/>
<img id='store_image_2' src='Images/test-shirt.jpg' alt='Back' class='fade_store'/>
</div>
</div>
I tried my hand it making it work, and it does, but if multiple store items are there when I go to the next store item the picture is the same as the picture I previously used. Here is the jquery I have written. I am using php to grab item information and image source to create new store items in case that is important.
$('.fade_store').mouseover(function(){
var currentPic = $(this).attr('src');
$('.fade_store').fadeTo(0.15);
$('.store_checkout_image').attr('src', currentPic);
});//end mouseover
Note, I would like to only change the the picture of the currently selected set of html divs. Currently If I have more than 1 set, the source of all divs with the class store_checkout_image will change.
Try this maybe ?
$('.fade_store').mouseover(function(){
var currentPic = $(this).attr('src');
$(this).parent().find('.fade_store:first').fadeTo(0.15);
$(this).parent().find('.store_checkout_image:first').attr('src', currentPic);
});//end mouseover
If you just want to update the first store_checkout_image element:
$('.fade_store').mouseover(function(){
var currentPic = $(this).attr('src');
$('.fade_store').fadeTo('slow', 0.15);
$('.store_checkout_image').eq(0).attr('src', currentPic);
});//end mouseover
Otherwise update eq(0) to point to the index of whichever element you need (0 points to the first element, 1 to the second, etc).
Also, the fadeTo call isn't working correctly, try adding a transition speed:
$('.fade_store').fadeTo('slow', 0.15);
http://jsfiddle.net/Hz7x2/4/

Changing name of all classes in html document with javascript

I have a List that shows Products. When I click on one, I need to change the class of the <li> so as to show that it is clicked. I got this working... But what I can't do is clear the other <li> that have been previously clicked so as to show it is not selected anymore.
This is part of my code, what am I doing wrong? btw, my logic here is to first refresh all classes to notselected, and then just update the list with my product id number. this can be seen on the second line of code.
I'm new to javascript, and did my research, and this is what I got.
function showdetails(ProductID) {
document.getElementsByName("ProductList").className = "notselected";
$("#"+ProductID).attr('class','selected');
Are you trying to do this?
function showdetails(ProductID) {
$("[name=ProductList].selected").removeClass('selected');
$("#"+ProductID).addClass('selected');
}
I think you need to iterate across all elements returned in document.getElementsByName("ProductList") and change className to each element individually.
var productLists = document.getElementsByName('ProductList');
for (i = 0; i < productLists.length; i++) {
productLists[i].className = 'notselected'
}

Categories

Resources