How to Scroll Down to a Specific Page Element in WordPress Using JQueryPosted on Updated on
Some sites have huge banner pictures that take up the full screen when it’s first loaded. Users then have to scroll down to read the content. While this might be suitable for many pages, there might be certain posts where you want visitors to be able to start reading immediately. Perhaps it’s a landing page for an advertising campaign and you want to present the content to your users as quickly as possible. Maybe a particular article or page is so important, that you want your users to start reading immediately. However, we don’t want to get rid of the banner for these pages – we just want to automatically scroll past it.
Whatever the reason, I will show you how to automatically and smoothly scroll to a certain page element in WordPress. You can modify the code so that it only scrolls on certain pages, and you can also customize the element depending on which page it is.
We’ll be using the jQuery library that comes automatically bundled in WordPress for this. Moreover, this solution won’t require you to create any files and place them on your server. Instead, we’ll be adding all the code inline using a new WordPress 4.5 function that wasn’t available earlier.
As a test example, here’s the element I want to scroll down to on my sample page:
The important part is highlighted in bold. Namely “h3:contains(‘Heading 2’)”. It says that we’re looking for an <h3> tag that contains the words “Heading 2”. You can modify this to identify any given element on your site. You can get a complete reference for selecting HTML elements using jQuery using the w3schools link.
Step 2: Enqueuing the Code in WordPress
If you don’t know how to add code to your WordPress installation, check out my earlier tutorial on the same.
The wp_add_inline_script function along with jQuery, allows us to have a smooth scrolling experience on WordPress. The technique is scalable for any number of pages with different scrolling requirements – just change the variable value to specify the new element with an appropriate “if” condition!
One Reply to “How to Scroll Down to a Specific Page Element in WordPress Using JQuery”!
Hi, this link is not working anymore: https://webhostinghero.org/how-to-add-code-snippets-to-wordpress/