Dym
Dym

Reputation: 61

JavaScript scroll to anchor

Having some problems with JavaScript / jQuery.

We're currently using a "shortcode" from Visual Composer (WordPress plugin) that creates (horizontal) tabs. We'we made some custom changes, but only visually (images/css).

We're trying to make it so that when you click on a tab you automatically scroll down to the content.

I've tried wrapping the script in

jQuery(document).ready( function({});
jQuery(window).ready( function({});

and also tried replacing .ready() with .load()

jQuery(".pws_tabs_controlls_item").children().click(function(){
    jQuery('html, body').animate({
         scrollTop: jQuery(".ts-fancy-tabs-container").offset().top
    }, 700, 'swing', function () {});
});

However! If you copy the entire script and paste it in the Console in Chrome/Firefox it will work as intended, based on that I'd say that the script it self works, it feels like it's not loading or registering or w/e.

Is there any (obvious) problem/mistake we've made?

I'd be happy to provide additional information if neccessary (e.g. the website address)

Any help would be greatly appreciated!

Upvotes: 1

Views: 140

Answers (1)

Buzinas
Buzinas

Reputation: 11725

The VisualComposer plugin renders only after the document is ready, and that's why it's not working.

The best way to solve your problem is by using jQuery's event delegation, e.g:

jQuery(document).on('click', '.pws_tabs_controlls_item > a', function() {
    jQuery('html, body').animate({
         scrollTop: jQuery(".ts-fancy-tabs-container").offset().top
    }, 700, 'swing', function () {});
});

UPDATE

After your comment, I can see that the anchor tags inside your .pws_tabs_controlls_item elements already have a click event listener, and it also uses event.stopPropagation(), so my code above will never be executed.

The other way to solve your problem, is by dirty-checking when the element is available, e.g:

function waitForAvailability(selector, callback) {
  if (jQuery('selector').length === 0) {
    callback();
  }
  else {
    setTimeout(function() {
      waitForAvailability(selector, callback);
    }, 0);
  }
}

And then, you can use the code you were already using, something like that:

waitForAvailability('.pws_tabs_controlls_item', function() {
  jQuery(".pws_tabs_controlls_item").children().click(function(){
    jQuery('html, body').animate({
      scrollTop: jQuery(".ts-fancy-tabs-container").offset().top
    }, 700, 'swing', function () {});
  });
});

Upvotes: 3

Related Questions