Thursday, April 12, 2012

Javascript - Jquery on the fly id retrieving

here's my problem, I've made an js with jquery that gives ids to divs and to links, witch are coordinated.


Ex :


div id="container"
 div id="1"
 div id="2"
 
 div id="links"
 a name="1"
 a name="2"
 


So once the page is loaded, when I click on the first a (name="1") it is supposed to show the first div (id="1").


But it seems that as my ids are created on the fly, the function doesn't seem to find the right div.


Here's my function :


$("#video_grid .grid_item a").each(function(i) {
 
 /*FINDING 'A' AND GIVING THEM NAME*/
 
 $(this).addClass("item"+(i+1));
 $(this).attr("name","#"+(i+1));
 
 /*BACKGROUND*/
 
 $(this).css("background-image", "url(images/visu_"+(i+1)+".jpg");
 $(this).hover(function(){
 $(this).css("background-image", "url(images/visu_hover_"+(i+1)+".jpg")
 },
 function(){
 $(this).css("background-image", "url(images/visu_"+(i+1)+".jpg");
 });
 });
 
 
 /*FINDING DIV GIVING THEM IDS*/
 
 $("#capsule_player > div").each(function(i){
 $(this).addClass("item#"+(i+1));
 });
 
 
 /*HERE'S THE PROBLEM*/
 
 $("#capsule_player div:first-child").css("display","block");
 /*appel la div correspondante avec la video*/
 $(".grid_item a").live("click",function () {
 var divname= $(this).attr("name");
 alert(divname);
 /*WORK FINE TIL HERE*/
 
 /*THIS IS THE REAL PROBLEM*/
 
 $(".item"+divname).show("slow").siblings().hide("slow");
 
 /*ALERT IF YOU FIND THE DIV WITH THE ID, DOES NOT WORK*/
 
 if ($(".item"+divname)[0]){
 alert('tonton');
 }
 
 });
 


I'm using Jquery, basic HTML and CSS, no php allowed, that's why I've made this code.
If you can help, i thank in advance !



Answer:

Your function that is supposed to give the div's their IDs is giving them a class. You should change it to something like this:
$("#capsule_player > div").each(function(i){
    $(this).attr("id", 'item' + (i+1));
});
That should work, but the rest of the code could do with a tidyup as there a better/more semantic ways to do what you want to do (which I might do when I'm not busy).
EDIT:
Something like this would be better (based on Armatus' comment):
// give each div a data-index attribute
$("div.item").each(function(i){
    $(this).attr("data-index", i);
});
// give each anchor a data-index attribute
$("#video_grid .grid_item a").each(function(i) {
    $(this).attr("data-index", i);
});

$(".grid_item a").live("click",function () {
    var index = $(this).attr("data-index");

    $('div.item[data-index="' + index + '"]').show();
});
.live() is deprecated, but I'll leave it because I don't know which version of jQuery you're using.

No comments:

Post a Comment