Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript scope and click events

I'm building an image slider and I am running into some issues with event handlers and scope.

Simple HTML setup like so:

<section>
  <div class="container">
    <div class="closer-look-slider">
        <ul>
            <li class="one"></li>
            <li class="two"></li>
            <li class="three"></li>
            <li class="four"></li>
        </ul>
    </div>
    <div class="clear"></div>
    <div id="closer-look-slider-nav">
        <button data-dir="left">left</button>
        <button data-dir="right">right</button>
    </div>
  </div>
  <div class="clear"></div>
  <div id="closer-look-slider-thumbs">
    <a href="javascript:void(0);" class="active">1</a>
    <a href="javascript:void(0);">2</a>
    <a href="javascript:void(0);">3</a>
    <a href="javascript:void(0);">4</a>
  </div>

</section>

In my code I have got event handlers to check when the navigation buttons are clicked and upon doing so it'll fire the relevant functions. This all works fine if I have one slider but as soon as I add another slider to the page it start's getting confused.

Here's the code for the click events:

slider.prototype.trigger_events = function () {
    _self = this;

    this.nav.on('click', function () {
        _self.set_slide_pos(jQuery(this).data('dir'));
        _self.transition();
        console.log(_self.nav);
    });

    this.thumbs_elem.on('click', function () {
        _self.pagination_index(jQuery(this));
        console.log(_self.thumbs_elem);
    });
};

If for example I have two sliders on the page (exact same markup) then both sets of buttons control the second slider rather than the one corresponding to the button being clicked.

I've played around a little bit and my guess is that it's something to do with the scope? here's what I get when I do some console logging.

slider.prototype.trigger_events = function () {
    console.log(this.nav) // returns both navigation items

    this.nav.on('click', function () {
      console.log(_self.nav) // always returns the second nav and not the one that was clicked
    });
};

Obviously this is causing me problems as regardless of whichever nav I click, it always controls the second one.

like image 419
woolm110 Avatar asked Feb 25 '26 10:02

woolm110


1 Answers

Your _self variable is implicitly global! Make it local to each trigger_events call by prefixing it with var (yes, it's a scope issue).

like image 161
Bergi Avatar answered Feb 27 '26 01:02

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!