Trying To Use Jquery .click function

Hey,

I am using a Jquery music player (Jplayer) and it works fine until I try to edit one component and track clicks from a link. You will see 2 things bolded:

1.) The unsuccessful attempt to use the Jquery .click function to trigger an alert when a link is clicked

2.) The Jplayer works great and lists all tracks, one on top of the other, where you see the track name and, if you click on it, the song plays. That works fine - the problem is the bolded part which I added. I added a hyperlinked shopping cart ‘buy now’ image which is located next to each track title.

In short, I need the bolded link part (the 2nd bolded part) to be recognized by a .click function so I can post it to a PHP page, get JSON and notify them that it was added to their cart.

The Problem: When I click on the link surrounding the ‘buy now’ image, nothing happens. Below is the code. Thank you.



function displayPlayList() {
    
    [B]$("a").click(function() {
     alert("Hello world!");
   });[/B]


        $("#jplayer_playlist ul").empty();
        for (i=0; i < myPlayList.length; i++) {
            var listItem = (i == myPlayList.length-1) ? "<li class='jplayer_playlist_item_last'>" : "<li>";
            listItem += "<a href='#' id='jplayer_playlist_item_"+i+"' tabindex='1'>"+ myPlayList[i].name +"</a> [B]<a href=''><img src='http://www.test.com/images/product_buy_2_transparent.gif' BORDER='0' align='right'></a>[/B]</li>  ";
            
                
            
            $("#jplayer_playlist ul").append(listItem);
            
            $("#jplayer_playlist_item_"+i).data( "index", i ).click( function() {
                var index = $(this).data("index");
                if (playItem != index) {
                    playListChange( index );
                } else {
                    $("#jquery_jplayer").jPlayer("play");
                }
                $(this).blur();
                return false;
            });
        }


PS. I am blocking out the rest of the code which controls the music player. That all works fine. The code you see references divs which I would have at the bottom of the page. If I could just get that link in the ‘for loop’ to be recognized, I can then create a var and pass the string to a php page and do the rest…thanks.

Try this

    $(document).ready(function(){
    $("a").click(function(){
        alert("Hello world!");
    });
});

Sadly, when I use that exact code in the function I posted (where the first part is bolded) it still doesn’t do anything.

When I take your code and put it outside of the function and outside of the first block of jquery, and use a link outside of jquery, it works fine. For reference, here is my entire jquery code (thank you):


 <script type="text/javascript">
$(document).ready(function(){

   $("a").click(function() {
     alert("Hello world!");
   });

 });
</script>

<script type="text/javascript">
<!--
$(document).ready(function(){

    var playItem = 0;
    
    // I need to make sure that this is some sort of JSON encoded string that loads all the proper songs

    var myPlayList = [
    
    <?
    
    include("json.php");
    
    ?>
        
    ];

    // Local copy of jQuery selectors, for performance.
    var jpPlayTime = $("#jplayer_play_time");
    var jpTotalTime = $("#jplayer_total_time");
{
        ready: function() {
            displayPlayList();
            playListInit(true); // Parameter is a boolean for autoplay.
        },
        oggSupport: true
    })
    .jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
        jpPlayTime.text($.jPlayer.convertTime(playedTime));
        jpTotalTime.text($.jPlayer.convertTime(totalTime));
    })
    .jPlayer("onSoundComplete", function() {
        playListNext();
    });

    $("#jplayer_previous").click( function() {
        playListPrev();
        $(this).blur();
        return false;
    });

    $("#jplayer_next").click( function() {
        playListNext();
        $(this).blur();
        return false;
    });
    
    function displayPlayList() {
    
    [B]$(document).ready(function(){
    $("a").click(function(){
        alert("Hello world!");
    });
});[/B]

        $("#jplayer_playlist ul").empty();
        for (i=0; i < myPlayList.length; i++) {
            var listItem = (i == myPlayList.length-1) ? "<li class='jplayer_playlist_item_last'>" : "<li>";
            listItem += "<a href='#' id='jplayer_playlist_item_"+i+"' tabindex='1'>"+ myPlayList[i].name +"</a> [B]<a href=''><img src='http://www.test.com/images/product_buy_2_transparent.gif' BORDER='0' align='right'></a>[/B]</li>  ";
            $("#jplayer_playlist ul").append(listItem);

            $("#jplayer_playlist_item_"+i).data( "index", i ).click( function() {
                var index = $(this).data("index");
                if (playItem != index) {
                    playListChange( index );
                } else {
                    $("#jquery_jplayer").jPlayer("play");
                }
                $(this).blur();
                return false;
            });
        }
        
    }
    
    function playListInit(autoplay) {
        if(autoplay) {
            playListChange( playItem );
        } else {
            playListConfig( playItem );
        }
    }

    function playListConfig( index ) {
        $("#jplayer_playlist_item_"+playItem).removeClass("jplayer_playlist_current").parent().removeClass("jplayer_playlist_current");
        $("#jplayer_playlist_item_"+index).addClass("jplayer_playlist_current").parent().addClass("jplayer_playlist_current");
        playItem = index;
        $("#jquery_jplayer").jPlayer("setFile", myPlayList[playItem].mp3, myPlayList[playItem].ogg);
    }

    function playListChange( index ) {
        playListConfig( index );
        $("#jquery_jplayer").jPlayer("play");
    }

    function playListNext() {
        var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
        playListChange( index );
    }

    function playListPrev() {
        var index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1;
        playListChange( index );
    }
});
-->
</script>


Below is div code that calls the main function which displays the tracks. I hope this helps.

Because you’re dynamically generating the markup that you’re trying to attach events to, you might want to try either the .live() or the [URL=“http://api.jquery.com/delegate/”].delegate() method.
(Or only call your event attacher after you’ve put the playlist in the document.)

Using .live() you “attach a handler to the event for all elements which match the current selector, now and in the future” (as per jQuery documentation).

e.g. of using .live():

$("#jplayer_playlist ul a").live("click", function() {
  alert("Hello world");
});

Works. I was wrong in thinking other links would be impacted by this. Like a dope, I had a 2nd ‘alert’ that I had to remove from the page.

The dynamic links now trigger the alert. Now, the goal is to take my hidden field with the value of track id
and pass it as a var. I’ll update this thread if I am stuck but hopefully I will be fine.

Thank you so much.

Actually, I do have just one last question as I don’t want to create a new thread (clutter).

I noticed in the ‘for loop’ the link for the track title has an id with a value = to the track ID. I want to add that to the link that hyper links the ‘buy now’ button and have that value captured as a variable. My attempt fails to deliver the value in an alert. Instead, I get an alert with the ‘Undefined’ message. Below is the code:


$("#jplayer_playlist ul a").live("click", function() {
[B]  var track_id=jQuery("#jplayer_playlist_item_" +i+ "").val()[/B]
  alert (track_id);
});

That is what is alerting the failed variable.

The following code is the link that is attached to the ‘buy now’ button with the ‘id=…’ code so I can hopefully capture the dynamic ‘track id #’ of any track clicked on when they try to add it to the cart.


<a href='#' [B]id='jplayer_playlist_item_"+i+"'[/B]><img src='http://www.test.com/images/product_buy_2_transparent.gif' BORDER='0' align='right'></a>

Curious as to what I am doing wrong. I can capture vars just fine when it’s a static link, just not when it is dynamic. That is still tricky for me.

Thanks for your time, guys.

Well, I realize I need to focus on ‘myPlayList[i]’, instead. For instance, to display tracks in the loop, as shown above, we have:


<a href='#' id='jplayer_playlist_item_"+i+"' tabindex='1'>"+ myPlayList[i].name +"</a> 

That displays the title of the song with a link that will play it once clicked on. I want to find a way to take the track ID (which I thought comes from +i+) and create a var. So I try to do that, as such:


$("#jplayer_playlist ul a").live("click", function() {
  var container = $("#"+i+" .myPlayList");
 
 alert (container);
});
    

The alert, instead of showing me the track ID of the track link I click on (when I click on ‘buy now’, not the track title) shows Object Object in the alert box. How can I get the variable to stick with the proper value of +i+ when I click on the dynamic ‘buy now’ link?

Thanks.

I want to take that

I’m guessing you want to get the value of the ID attribute of the first link
i.e.: jplayer_playlist_item_ + i

It would probably be best if you would put a class on the link of which you would like to grab the ID, for example I added the class “playlistItem” on the link that has the ID:

<a href='#' id='jplayer_playlist_item_"+i+"' class='playlistItem'><img src='http://www.test.com/images/product_buy_2_transparent.gif' BORDER='0' align='right'></a>

Then in your click handler:

$("#jplayer_playlist ul a").live("click", function() {
  var track_id= $(this).closest("li").find(".playlistItem").attr("id");
  alert (track_id);
});

Note: inside jQuery event handlers, the “this” keyword references the element that triggered the event. In this case, it would be either the playlist item link or the buy now link. (Which is why we need to identify which of the links is the playlist item and which is the buy now link.)

Thank you! I am not advanced enough to know how to do that before tonight. I will make more examples like this and study more of these events in the jquery api.

Now, I guess I can just pass this to a php page, use getJson and then print out the shopping cart data whenever I want. HUGE help. Thank you, once again. Have a good night.