Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.attr() works fine on Google Chrome and IE, but fails on Firefox 8.0.1

I'm facing a curious behavior of Firefox 8.0.1 : this piece of code works fine on Google Chrome and in IE, but on Firefox it fails except if I run it in 'debug mode _ step by step' or if I put an alert just after the line where I set the attribute "rel"...

// some stuff before
// this piece of code works fine excepts on FF
        totaltracks = data.length;
    j=0;
    while(j<totaltracks){
        newtrack =data[j];
        myPlaylist.add(newtrack);
        tracks = $("a.jp-playlist-item");
        curtrack =  $("a.jp-playlist-item")[j];
        $(curtrack).attr({rel:j});
        // I tried too : $("a.jp-playlist-item")[j].attr("rel",j); with same no effect on FF
        j++;            
    }    

It seems FF just don't take care of the instruction (or jump it) if not done step by step ... 2 days passed facing this wall ... any help/clue/trick would be much appreciated

like image 770
phron Avatar asked Dec 10 '11 09:12

phron


1 Answers

Although I find the specifics of what you are doing a little peculiar, I tried to find a more stable way to accomplish it. It seems plausible that the inconsistent behavior you are seeing is due to timing issues. The "alert", "debug stepping" and "setTimout" hacks all point in that direction.

First, some feedback on your code

totaltracks = data.length;
j=0;

// I preferably use $.each() in these type of situations.
// See http://api.jquery.com/jQuery.each/
while(j<totaltracks){
    newtrack =data[j];
    myPlaylist.add(newtrack);

    // Here you select the same DOM elements for every loop of the while statement.
    // This is a performance issue.
    tracks = $("a.jp-playlist-item");

    // Here you select the those DOM elements once again,
    // then you assign the j:th element to the curtrack variable.
    // This doubles the performance issue.
    curtrack =  $("a.jp-playlist-item")[j];

    $(curtrack).attr({rel:j});
    j++;            
}

I do believe that these performance issues possibly could be the cause of your problems.

Second, my suggestion

// Select the DOM elements only once.
var trackElements = $("a.jp-playlist-item"),
    trackData = [
                    {title: 'Stuck in a groove', artist: 'Puretone'},
                    {title: 'Addicted To Bass', artist: 'Puretone'},
                    {title: 'Hypersensitive', artist: 'Puretone'}
                ];

$.each(trackData, function(index, newTrack){
    myPlaylist.add(newTrack);
    $(trackElements[index]).attr("rel", index);
});

Third, the full example

I created this fiddle for you to play around with. It demonstrates my suggestion in a more complete manner. Hopefully this points you in the right direction.

like image 114
Benny Johansson Avatar answered Sep 24 '22 15:09

Benny Johansson