How to scroll click
How to scroll click
How to create a Horizontal Scroll on button click using JavaScript?
If you’re just looking for a CSS based solution without clicks, I’ve got you covered in this post:
Let’s add the simple HTML container and contents inside. I have tried to include links since mostly we need this kind of scrolling with a bunch of links. Also, add the buttons to indicate the scrolling direction.
Currently the width is 100% so no need to scroll. Let’s make it a smaller window where the content is required to scroll. Also, let’s make a bit nice looking with minimal style changes.
As you must have noticed, the scrolling is already working when try to slide left or right using mouse pad.
JavaScript
Let’s create the JavaScript function and add onclick attribute for the buttons in HTML.
Here’s the function and working demo:
Let’s understand line by line.
Using HTML onclick attribute, I am calling a function slide with a value since the JavaScript function requires a direction parameter.
In the function itself, we are getting the main container using getElementById. I have set the variable scrollCompleted to 0 since initially there won’t be any distance covered.
After that I am using setInterval method to create the sliding effect in timely manner. You can change the speed of the scroll by changing the setInterval function time.
Inside the setInterval function, I am just checking if the variable passed on the click was left or right and according to that value I am adding to subtracting a specific value — which you can change as per your requirements. I am using scrollLeft to do so.
Also, everytime we add or subtract a value, we need to increment the value of scrollCompleted variable since that will keep an eye on distance covered (scroll completed).
Finally, we need to stop scrolling at a certain point which in this case I am stopping the scroll when it covers 100px. Keep in mind that I am talking about a stopping on a single click that means on a single click I am making the content shift 100px left or right based on the click.
That’s it. After each click it will cover 100px and it’ll stop at the end when there is no more distance to cover.
There are few ways to do the same horizontal scrolling. This is just one way to do it.
Scroll to an element on click in React js
Today we will learn how to scroll to a particular element by clicking on a certain element. This is beneficial if you are creating a single page application and where users click on a particular menu item then he will be scrolled to that referring element. So let us see how to implement that in our React project.
Requirments
2. Now open terminal inside your react js project and install react-scroll
3. Go to your src folder and create a components folder.
4. Now inside your components folder create your first component with the name header.js
5. Open the header.js file in your code editor. I will create a simple menu inside that file so paste the below code inside the header.js file. I have also added some inline styling.
6. Again go to your components directory and create another component with the name middleSection.js. Inside that component, I will add some dummy content with a unique id referring to the menu items.
7. Now its time to use react scroll. Go again to your header.js file and import Link from react-scroll
8. Now wrap your menu items with the Link tag and pass some props like below.
Props Used
9. Now import components to the app.js file and start the application to see changes.
Below I have shared live and code and GitHub repository for reference.
How to scroll to element after click event and new page load with Vanilla JavaScript
I will try to summarize this in a Requirements fashioned way, I hope this simplifies the question.
When clicking on an anchor tag, the web page navigates the user to a new page, where upon page load, the page is scrolled to the element which corresponds to the aforementioned anchor tag, which was previously clicked.
As you will see in the code I am trying to make use of the CSS scroll-behaviour property. https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior
So far I have tried out the code bellow, however when I run it I get an error message in the developer console stating:
TypeError: Cannot read property ‘offsetTop’ of undefined
Hence, I surmise that the window.onload function is not really fired on the page which I would like to load but the very same page on which I am located when clicking the anchor tag. How can I change the code so it would count for page intended.
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The reason you’re getting the error is it’s impossible to run javascript across page loads. Assuming you’re using a traditional site and not a single-page app, when the browser loads a new page, all javascript on the current page is stopped.
Browsers already support jumping to an element on page load using the www.site.com#myElementId syntax. If you want smooth scrolling, you’ll need to pass the id of element to scroll in the url, or some other way like caching its id in localstorage, then run your smooth scrolling js on the pageload of the other page.
You can’t navigate to a different page and then ask the browser to launch a piece of JavaScript. That would be a huge security issue, since I could make you click into a link to, let’s say, my-bank.com then do a bit of JavaScript do access your secret cookies or local storage and hack into your account.
The only thing you can do is link to anchors inside the linked page, and the default scroll behavior (no smooth scrolling, for most browsers, since it’s the least computationally and resources intensive) will be used:
If you own the target page, however, you can hide a target section in the query string then do a bit of magic in the target page’s onload to smoothly scroll to your section:
There are two methods to smoothly scroll a web page after clicking the anchor link which are discussed below:
Method 1: Using scrollIntoView() with the ‘smooth’ behavior: The scrollIntoView() method is used to scroll the view of the user to the element that it is called upon. It contains several options that may be defined to modify the scroll behavior. One of these is ‘behavior’ property. The default value of this property makes the scroll instantly jump to its destination, instead of smoothly scrolling. Setting this value to ‘smooth’ changes this behavior and makes the page scroll smoothly.
The hash portion of the anchor link is first extracted using the hash property and it is selected with the querySelector() method. The scrollIntoView() method is then called on this selected element to smoothly scroll the page to this location.
Example:
Output:
Method 2: Using jQuery scrollTop() method: The scrollTop() method in jQuery is used to scroll to a particular portion of the page. Animating this method with the available inbuilt animations can make the scroll smoother.
The hash portion of the anchor link is first extracted using the hash property and its position on the page is found out using the offset() method. The scrollTop() method is then called on this hash value to scroll to that location. This method is animated by enclosing it within the animate() method and specifying the duration of the animation to be used in milliseconds. A larger value would make the animation slower to complete than a smaller value. This will smoothly animate all the anchor links on the page when they are clicked.
Как прокрутить экран с помощью среднего щелчка?
В Windows большинство программ с большими прокручиваемыми текстовыми контейнерами (например, все браузеры, большинство текстовых процессоров и IDE) позволяют нажимать среднюю кнопку мыши, а затем перемещать мышь для прокрутки. Эта прокрутка плавная и позволяет вам очень быстро прокручивать, используя только мышь.
Я не уверен, как добиться того же при запуске Linux на рабочем столе с помощью мыши. Насколько я могу судить после целой кучи Google, нет ни специфичных для приложения настроек для переключения на поведение средней кнопки мыши в стиле Windows, ни каких-либо общесистемных настроек для достижения того же эффекта.
Насколько я могу судить, мои варианты прокрутки:
Итак, мои вопросы:
Однако в Firefox есть настройка предпочтений и расширение, доступное для Chrome / Chromium, которое позволит вам использовать среднюю кнопку мыши для прокрутки и активировать эту функцию.
Fire Fox
Хром / Хром
Нажмите на кнопку с надписью, ADD TO CHROME чтобы установить это расширение.
Нажмите Add в диалоговом окне подтверждения.
Другие приложения
Что касается других приложений, я пока не нашел решения для них. В любом случае, это высокие веб-страницы, которые создают большую часть проблемы, для которой у Firefox и Chrome / Chromium есть решение.
Источники информации:
- http://medium.com/how-to-react/scroll-to-an-element-on-click-in-react-js-8424e478bb9
- http://stackoverflow.com/questions/57010682/how-to-scroll-to-element-after-click-event-and-new-page-load-with-vanilla-javasc
- http://www.geeksforgeeks.org/how-to-set-smooth-scroll-after-clicking-the-link-using-javascript/
- http://qastack.ru/unix/58900/how-to-scroll-the-screen-using-the-middle-click