Marley
Marley

Reputation: 185

Swiper onSlideClick - Get clicked HTML element

There's probably a very easy way to solve my problem...

My (simplified) HTML:

<div class="swiper-container">
    <div class="swiper-wrapper">
        <div class="swiper-slide">
            <a id="user-link" href="#" data-user-id="47">..</a>
            <a id="post-link" href="#" data-post-id="8">..</a>
        </div>
    </div>
</div>

Now, what I need is a simple way to determine which link was clicked, so I can redirect to different pages. Somehow it's not possible with the given "onSlideClick" function from the Swiper API.

I've been trying something like this:

onSlideClick: function() {
    if ($(this).attr('id') == 'user-link') {
        var userId = $('a').data('user-id');
        $.redirect('user.php', { userId: userId });
    }
    if ($(this).attr('id') == 'post-link') {
        var postId = $('a').data('post-id');
        $.redirect('post.php', { postId: postId });
    }
}

Problem: Firebug tells me that

onSlideClick: function() {
    console.log($(this).attr("id"));
}

is undefined.

I have to redirect via JavaScript, otherwise my swipes won't work, because I get redirected immidiately.

Upvotes: 0

Views: 2629

Answers (1)

Vladimir  Kharlampidi
Vladimir Kharlampidi

Reputation: 9867

You can try to get clicked element from event target:

onSlideClick: function(swiper, e) {
  var clicked = $(e.target);
  var id = clicked.attr('id');
  if (id == 'user-link') {
    var userId = clicked.data('user-id');
    $.redirect('user.php', { userId: userId });
  }
  if (id == 'post-link') {
    var postId = clicked.data('post-id');
    $.redirect('post.php', { postId: postId });
  }
}

Upvotes: 1

Related Questions