I'm making an image gallery in which I want the user to be able to click on a thumbnail and get a bigger image displayed.
This is the php-code to iterate over all images in a directory on the server and display them and give them each a unique id.
echo '<div id="image' . $i . '" class="image">' . $thumbsrc . '</div>';
echo '<div id="bigimage' . $i . '" class="bigimage">' . $imagesrc . '</div>';
This works fine, I use
$(".bigimage").hide();
to hide the bigger images.
So what I could do now is this:
$("#image1").click(function() {
$("#bigimage1").show();
});
$("#bigimage1").click(function() {
$("#bigimage1").hide();
});
But I find for up to 30 pictures I can't write 30 instances of this so I wanted to loop it.
I tried
for (var i = 1; i < 30; i++) {
$('#image' + i).click(function() {
$('#bigimage' + i).show();
});
$('#bigimage' + i).click(function() {
$('#bigimage' + i).hide();
});
}
Which doesn't seem to work? Why not?
If I do
for (var i = 1; i < 10; i++) {
$('#image' + i).append('<p>test' + i + '</p>');
}
it appends paragraph's to every #image-element so looping selector's seem to work.
How would I do this?
Thanks beforehand.
That's because all of your click handlers use the same value, for understanding what happens, you can refer to this question: Javascript infamous Loop issue?
Since your elements have classes, you can use you classes instead. index method returns the index of the passed element in a collection. After getting the index, for selecting the corresponding element in another collection you can use the eq method.
var $img = $('.image');
var $bigImg = $('.bigimage').hide();
$img.on('click', function() {
var i = $img.index(this);
$bigImg.eq(i).show();
});
$bigImg.on('click', function() {
// this keyword refers to the clicked element
$(this).hide();
});
Related
I am adding buttons based on an array. The problem I am having is that every time I add another name to the array, it prints out all the buttons not just the one I added. I am wondering how would I erase all the old buttons before I add the array of buttons.
Here is my code
socket.on('usernames', function(data){
console.log(data);
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
// $users.html(html);
});
Below is an image. Test is the name of the first button and every time I add a new button it prints the entire array again. Is there a way to delete the old buttons?
Use the empty() method before you loop:
socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for (i = 0; i < data.length; i++) {
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($contentWrap);
}
});
Also note that you can improve performance and tidy the code by creating a single HTML string and setting the html() property to only require one DOM call. Try this:
socket.on('usernames', function(data){
var html = data.map(function(value) {
return '<input type="button" value="' + value + '"/></br>'
}).join('');
$('#contentWrap').html(html);
});
You can call .empty() on the parent element before appending the elements again.
$("#contentWrap").empty();
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
I have a dependent drop down i.e. State -> city -> Pincode .
I am using json instead of fetching from the database .
The dropdown works fine on the local server .
But on the web-server it is relatively slow .
A part of code, is here -
for (var i = 0; i < pincodes['address'].length; i++) {
if (pincodes['address'][i]['regionname'] == city_key) {
$('#pincode').append('<option>' + pincodes['address'][i]['pincode'] + '</option>');
}
}
what are the ways , I can implement to make it load faster .
I recommend you concatenate your option HTML to a single string, so you can insert it all at once.
43,439 reasons to use append() correctly
var optionInsert = '';
for (var i = 0; i < pincodes['address'].length; i++) {
if (pincodes['address'][i]['regionname'] == city_key) {
optionInsert += '<option>' + pincodes['address'][i]['pincode'] + '</option>';
}
}
$('#pincode').append(optionInsert);
I'm trying to make a simple timeline that informs users. When they click on a date, there should be some sort of "accordion" system that drops down and give more information. When they click on it again, the "accordion" closes again.
I've included some pictures to make it somewhat more clear:
And:
The first image shows what the user is seeing when he gets onto the page, the second picture shows what he sees when he clicks on 1 of the elements.
The problem ive at the moment is when he clicks on 1 day, all the information is shown. I dont know how i can get some sort of index so only that particular day shows its hidden information.
At the moment I've the following code:
JavaScript
$counter=1;
$(document).ready(function(){
$(".tijdlineElement").click(function(){
$(".tijdlineElementHidden").slideToggle("slow");
if($counter == 1){
getElementsByClassName("tijdlineElementHidden").style.display = "block";
$counter = 2
}
else{
getElementByClass("tijdlineElementHidden").style.display = "none";
$counter =1
}
});
});
and the PHP to make 1 Day:
echo "<div class='tijdlineElement'>";
echo "<div class='tijdlineP2Element' >" . $topic['Uur']."<br /><br />" . $topic['Beschrijving'] . "</div>";
echo "<div class='tijdlinePElement'>". $newDate . '<br />'. $newDate1 . ' '. $newDate1a . '<br />' . $newDate2 ."</div>";
echo "<img src='images/meerFase1.png'/>";
echo "</div>";
echo "<div class='tijdlineElementHidden' style='display:none;'>";
echo "<div class='tijdlineP2Element'>" . $topic['LangeBeschrijving'] . "</div>";
echo "<div class='tijdlinePElement'></div>";
echo "</div><br />";
The issue is, when a user clicks on 1 date, all the information from the other days get revealed aswell.
So my question is: How can i get access to that particular div, so only the information from the selected(the div that was clicked on) div is shown?
With your current code by using $(".tijdlineElement").click(function(){ } You are triggering the click event on all elements with that class. What you could do is use something like .each() and $(this) to scope it to your currently clicked element.
$(".tijdlineElement").each(function(){
$(this).on({
click:function()
{
$(this).slideToggle("slow");
// other click function stuff
}
});
});
Quick Demo:
http://jsfiddle.net/9v2D5/
Updated Demo:
http://jsfiddle.net/9v2D5/25/
Loop through all elements that share the same class name, then addEventListener or attachEvent if IE8. (Native JS solution)
var elements = document.querySelectorAll(".tijdlineElement");
var i = 0, length = elements.length;
for (i; i < length; i++) {
if (document.addEventListener) {
elements[i].addEventListener("click", function() {
var element = this;
});
} else { // IE8 support
elements[i].attachEvent("onclick", function() {
var element = elements[i];
});
};
};
Instead of referencing the class, use $(this) to reference it:
$(".tijdlineElement").click(function(){
$(this).find(".tijdlineElementHidden").slideToggle("slow");
.....the rest of the code...
}
Try this:
var parent = $( this );
$( ".tijdlineElementHidden", parent ).slideToggle("slow");
It should toggle only the "tijdlineElementHidden" divs that are children to the clicked element.
I am bringing a feed of a youtube user's video channel onto a page via two plugins called jYoutube and jGFeed.
jGFeed: http://archive.plugins.jquery.com/project/jgfeed
jYoutube: http://archive.plugins.jquery.com/project/jyoutube
I am getting stuck on why this isn't working... I thought it would be as easy as a simple if/else statement, but it is not working.
jQuery(document).ready(function($) {
$.jGFeed('http://gdata.youtube.com/feeds/base/users/POTATOwillEATyou/uploads?alt=rss&v=2&orderby=published&client=ytapi-youtube-profile',
function(feeds){
// Check for errors
if(!feeds){
// there was an error
return false;
}
var html = '';
// do whatever you want with feeds here
for(var i=0; i<feeds.entries.length; i++){
var entry = feeds.entries[i];
//My attempt at alternating classes:
if((i%2) == 0)
{
console.log('hello')
$(".thethumb").addClass("even");
}
else
{
console.log('NOPE')
$(".thethumb").addClass("odd");
}
//End of my attempt
html += '<a rel="vidbox" class="thethumb" target="_blank" href="' + entry.link + '" title="' + entry.title + '"><img src="' + $.jYoutube(entry.link, 'small') + '" class="thumb left"></a>';
}
$('#you_tube_feed').html(html);
}, 25);
});
Your issue is that you are are changing the class of ALL .thethumb, and they don't exist at the time you're running that code (they're inside your html string)
for(var i=0; i<feeds.entries.length; i++)
{
var entry = feeds.entries[i];
var $new = $('<a rel="vidbox" class="thethumb" target="_blank" href="' + entry.link + '" title="' + entry.title + '"><img src="' + $.jYoutube(entry.link, 'small') + '" class="thumb left"></a>');
if((i%2) == 0)
{
$new.addClass("even");
}
else
{
$new.addClass("odd");
}
$('#you_tube_feed').append($new);
}
Since you are using JQuery, it's even more simple . . . add all of the thumbnails first and then go back use the :even and :odd selectors to add the classes all at once:
$('.thethumb:even').addClass('odd');
$('.thethumb:odd').addClass('even');
You'll noticed that the classes are switched in comparison to the selectors . . . that is because the JQuery selector is 0-based, so items "0", "2", "4", etc. are actually the 1st, 2rd, 5th, etc. items in the selection.
I'm working on creating a service that allows you to create team or user based challenges. Using HTML 5 specifications to design the page, I've run into a bit of an issue appending to a drop down list that resides in another page. The entirety of functionality lives within two pages, mainly by making AJAX calls to other pages. There's a little function that appends 2 properties of a team to a drop down list, but I can't seem to get it to work properly.
Code:
var teams = $.parseJSON(getAllTeams());
$('#multiPurpose').load('allTeams2.html #teamSelect');
for (i = 0; i < teams.length; i++) {
var team = $.parseJSON(getTeam(teams[i]));
if (team.ownerID === userID) {
$(
"<option value='" + team.teamID + "'>" + team.teamName
+ "</option>").appendTo('#teamSelection');
}
}
}
The #teamSelection is contained within the #teamSelect div. Any help would be great.
Adding a callback function within .load() will solve the problem. Basically, you're telling it to load everything within that div before running the for loop.
$('#multiPurpose').load(
'allTeams2.html #teamSelect',
function() {
for (i = 0; i < teams.length; i++) {
var team = $.parseJSON(getTeam(teams[i]));
if (team.ownerID === userID) {
$(
"<option value='" + team.teamID + "'>"
+ team.teamName + "</option>")
.appendTo('#teamSelection');
}
}
});