Claire
Claire

Reputation: 3785

How do I add an onclick function to all matched elements

This function only works once, when I click an anchor element again, nothign happens. I thought the selector would apply the .click function to all matched elements?

 $('#welcome-nav li a').click(function (e) {
   // prevent anchor from firing
    e.preventDefault();

    var chosenElement = $(this).parent().attr('class');
    var index = articles.indexOf('.' + chosenElement) + 1;


   //remove all classes of active on articles
    $.each(articles, function (index, value) {

       $(value).removeClass('active');
   })

    $('.' + chosenElement).addClass('active');
    $('#sharpContainer').bgStretcher.sliderDestroy();
    startBgStretcher(returnImageArray(index));


 })

Below is the plugin that I think is breaking the onclick function

    $('#sharpContainer').bgStretcher({

        images: imageContainer,
        anchoring: 'left top', //Anchoring bgStrtcher area regarding window
        anchoringImg: 'left top',   //Anchoring images regarding window
        nextSlideDelay: 8000, //Numeric value in milliseconds. The parameter sets delay until next slide should start.
        slideShowSpeed: 2000, //Numeric value in milliseconds or(’fast’, ‘normal’, ’slow’). The parameter sets the speed of transition between images
        transitionEffect: 'superSlide',
        slideDirection: 'W',
        callbackfunction: homepageSlide
    });



function homepageSlide() {

    //homepage slide is called after a slide has loaded
    var index = $('li.bgs-current').index();

    //hide current article
    $.each(articles, function (index, value) {

        $(value).removeClass('active');
    })

    //show next article
    $(articles[index]).addClass('active');


}

Upvotes: 1

Views: 2952

Answers (3)

Sammaye
Sammaye

Reputation: 43884

I think this might be due to the way JQuery binds by default. If you use:

$(document).on('click', '#welcome-nav li a', function(e){
    e.preventDefault();
    alert('here');
});

What happens?

Edit

Example of static element usage

$('#welcome-nav li').on('click', 'a', function(e){
    e.preventDefault();
    alert('here');
});

Upvotes: 4

Seimen
Seimen

Reputation: 7250

I would bind it like this:

$('#welcome li').on('click', 'a', function(e) {
    e.preventDefault();
    whatever();
});

Upvotes: 0

You could try the simple "return false;" after doing all the things you want to do in the .click event function.

Upvotes: 0

Related Questions