SOFuser123
SOFuser123

Reputation: 105

unable to invoke onclick for handlebar span class

I am facing problem with jquery onclick event and handlebars.

I have a handlebars template with ul,li and span elements forming a horizontal navigation menu. I have a class defined for each of the span,writted css class for hover and selected.

Hover works fine but if i select the span element i dont get redirected to onclick event present in one of the included JS files.

This is my handlebar template.

var policyMenu = '<ul class="menu menuStyle"><li style="float:left;"><span class="mn selected" rel="environmental" title="Environmental policy" >Environmental</span></li><li style="float:left;"><span class="mn" rel="employee">Employee</span></li><li style="float:left;"><span class="mn" rel="customer">Customer</span></li><li style="float:left;"><span class="mn" rel="assets" >Assets</span></li></ul><br><br><br><div id="chart_container" style="min-width:39%;"></div>';

var policy_template = Handlebars.compile(policyMenu);

here is my JS code which is inside a included jS file

alert($('ul.menu li span.mn'));
 $('ul.menu li span.mn').click(function(){
    alert("menu function");
    if ( $(this).hasClass('selected') )
        return;     
    $('ul.nav li span.mn').removeClass('selected');
    $(this).addClass("selected");

    selectedMenu = $(this).attr('rel');     
    alert(selectedMenu);
    //getResourceData(selectedSCA,'',0,0,0,0,0);
    displaySearchOptions();
});

I am unable to print the alert inside onclick.

Upvotes: 1

Views: 815

Answers (1)

emerson.marini
emerson.marini

Reputation: 9348

You should use delegation, as your new elements are not present on the DOM tree at the moment you load the script. This way, the event handler will be attached to every new element that attends the selector.

$(document).on('click', 'ul.menu li span.mn', function() { 
    if ( $(this).hasClass('selected') )
        return;     

    $('ul.nav li span.mn').removeClass('selected');
    $(this).addClass("selected");

    selectedMenu = $(this).attr('rel');     
    displaySearchOptions();
});

Source: http://api.jquery.com/on/

Upvotes: 2

Related Questions