Search code examples
javascriptjqueryevent-handlingmustachejquery-events

Jquery On() 'click' working on every thing?


I have a problem which drive me crazy :( Couldnt figure it out why!

Here is my HTML and Mustache

<section id="slideShow">
    <script id="slideShow-template" type="text/template">
        <ul>
            {{#slideShow}}
            <li class="{{{class}}}">
                <img src="{{{img}}}" alt="{{{title}}}">
                <a href="{{{link}}}">
                    <h1 class="slideShowTitle">{{title}}</h1>
                    <p class="slideShowDate">{{date}}</p>
                    <p class="slideShowDetail">{{detail}}</p>
                </a>
            </li>
            {{/slideShow}}
        </ul>
        <nav>
            {{#slideShow}}
                <a href="javascript:;"></a>
            {{/slideShow}}
        </nav>
        <a href="javscript:void(0)" class="prevSlide"></a>
        <a href="javscript:void(0)" class="nextSlide"></a>
        
    </script>
</section>

and here is the JS

(function() {

    var slideShow = {
        slideShow: [
        ],

        init: function() {
            this.cacheDom();
            this.bindEvents();
            this.render();
        },

        bindEvents: function() {
            this.$el.on('click', this.$next, function(){
                alert('sdsd')
            })
        },

        render: function() {
            var data = {
                slideShow: this.slideShow
            };
            this.$el.html(Mustache.render(this.template, data));
        },

        cacheDom: function() {
            this.$el = $('#slideShow');
            this.$ul = this.$el.find('ul');
            this.$li = this.$ul.find('li');
            this.$nav = this.$el.find('nav');
            this.$a = this.$nav.find('a');
            this.$next = this.$el.find('.nextSlide');
            this.$prev = this.$el.find('.prevSlide');
            this.template = $('#slideShow-template').html();
        }

    };

    slideShow.init();

})();

as you see with bindEvents(), I'm trying to bind click function to the dynamically generated .nextSlide tag but it works on whole parent (#slideShow) what am I missing?

THE FIDDLE


Solution

  • Change this:

        this.$el.on('click', this.$next, function(){
            alert('sdsd')
        })
    

    to this:

        this.$el.on('click', '.nextSlide', function(){
            alert('sdsd')
        })