Using jQuery to center the target ID element of an href on the page with scrollIntoView

I'm interested in how to use the scrollIntoView method to scroll an element with a specific target ID to the center of the page when clicking on a link.

Here's the code I currently have:

$("a").click(function () {
    var target = $($(this).attr("href"));
  
    target[0].scrollIntoView({
      behavior: "smooth", 
      block: "center"
    })
  });

I've been able to successfully log the targeted element and make changes using other methods, but I'm struggling to figure out how to center it when scrolling.

You can view an example of what I'm trying to achieve in this Codepen, which uses scroll-margin-top: 50vh instead.

Any help would be greatly appreciated. Thank you!

Answer №1

It appears that your code is functioning correctly for me. The problem could be related to the href not being a valid css selector or the element not being accessible within the scope of your code.

To troubleshoot, consider adding console.log(target) to the callback function or logging target[0] to verify if it is the desired target.

Below is an example snippet demonstrating the use of .scrollIntoView:

(async () => {
  const $ = str => document.querySelector(str);
  const wait = t => new Promise(r => setTimeout(r, t));
  
  const section1 = $("section");
  const section2 = $("section:nth-of-type(3)");
  const options = {
    behavior: "smooth",
    block: "center"
  }
  while (true) {
    await wait(3000);
    section2.scrollIntoView(options);
    
    await wait(3000);
    section1.scrollIntoView(options);
  }
})();
body {
  margin: 0;
  height: 300vh;
  background: linear-gradient(black, lightgray);
  
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

section {
  height: 20px;
  width: 100%;
  background-color: rgba(30, 30, 255, 0.8);
}
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arrange JSON objects by priority before randomizing all other elements

Seeking assistance as I am unable to solve this on my own :( I have a list of JSON objects: {"widget_foto": {"photos": [ { "picThumb": "../../preview_stuff/img/widget-3-1.png", "picOrig": "../../preview_stuff/img/widget-3-1.png", ...

Calculating the time gap between two consecutive "keyup" occurrences

I am in need of creating a basic point of sale system using Javascript. I have a barcode scanner that functions like a keyboard. My goal is to automatically identify when the input is coming from the barcode scanner and then generate a report with the sc ...

angular model bind include move

I'm working on developing custom elements that will transform my form elements to match the styling structure of Bootstrap's forms. Essentially, <my-input ng-model="myname"> should be transformed into <div class="form-element"> ...

Tips for activating text selection in PDF.js

Struggling to enable text selection in PDF.js after successfully displaying a PDF? Seeking a simple example to guide you through the process? Despite trying various approaches, I haven't achieved the desired outcome yet. My current code snippet is a ...

What is the best way to loop through an array of objects using oboe?

Recently, I received a JSON response structured like this: [{ "id": 425055, "title": "Foo" }, { "id": 425038, "title": "Bar" }, { "id": 425015, "title": "Narf" }] To handle this data, I decided to utilize oboe.js to generate a highland stream ...

The method of implementing an index signature within TypeScript

I'm currently tackling the challenge of using reduce in Typescript to calculate the total count of incoming messages. My struggle lies in understanding how to incorporate an index signature into my code. The error message that keeps popping up states: ...

Trigger refetchQueries post-execution of a mutation operation

In the past, I executed a mutation in a similar manner as shown below: export const useEditLocationName = () => { const [editFavoriteLocationName] = useEditFavoriteLocationNameMutation({ refetchQueries: [{ query: GetMyFavouritePlacesDocument}], ...

What is the method for modifying the text color of P tags within a div element?

I'm having trouble changing the text color of the P tags in the card-header section for some reason dashboard.html <div class="container"> <div class="card"> <div class="card-header"> <p& ...

Using React Native to trigger a function based on a conditional statement

<Pressable onPress={()=> { if(newID) { EditPress(newID) } else { AddPress } }} style={styles.logBox} > <Text style={{ textAlign:"center", ...

Scripting issues detected in Safari and Microsoft Edge browsers

I recently finished developing an AngularJs Application that works flawlessly on Google Chrome and Mozilla Firefox. However, upon testing it on Safari and IE-11, I encountered errors in the console. One particular piece of code that causes issues is used ...

"The challenge of achieving a transparent background with a PointMaterial texture in ThreeJS

When creating a set of particles with THREE.Points and using a THREE.PointMaterial with texture, I noticed that the transparency of the particles is working only partially. The textures are stroke rectangles created with canvas. Here is what my particles ...

Exploring jQuery Mobile | Moving Seamlessly between Pages

I'm relatively new to JQM and I'm working on creating a mobile application using jQuery Mobile. Here's the goal I'm aiming for: I have multiple HTML pages, each with its own CSS, JavaScript, and JQM components. What I want is to be ab ...

Using AngularJS to fetch images from RSS feed description

I'm currently learning AngularJS by creating a simple RSS feed. I have successfully made a JSON request and fetched all the data including title, link, description, and images from the RSS feed I parsed. The code snippet for extracting images looks li ...

What is the best way to create an impact?

Need help fixing the parallax effect on this page. I attempted to implement a parallax effect but encountered some issues. Here is the JavaScript code: $objWindow = $(window); $('section[data-type="background"]').each(function(){ var $bgOb ...

Retrieve all the values from a form with identical names using angularjs

I have a form with two text boxes, one for entering a name and the other for an email. There is also a button to add a new row with these two text boxes. I am attempting to retrieve the values of Name and Email using AngularJS, but I am new to Angular. Be ...

Press on a specific div to automatically close another div nearby

var app = angular.module('app', []); app.controller('RedCtrl', function($scope) { $scope.OpenRed = function() { $scope.userRed = !$scope.userRed; } $scope.HideRed = function() { $scope.userRed = false; } }); app.dire ...

Include a border around the image on the overlay, along with a close button or link

Looking for some help with my code that opens images in an overlay div. I am struggling to add a border to the image object, as it only displays the raw image without any border. How can I modify this code to include a border around the image and also ad ...

What is preventing the direct passing of the dispatch function from a useState hook into an onClick handler function?

const Counter = () => { const [count, setCount] = useState(0); // Uncommenting the line below would result in an infinite loop because it directly invokes setCount(count + 1) on render. // This causes the component to continuously re-render and up ...

Issue with the 5-day forecast from the Openweather.com API

Today marks my inaugural use of the openweather.com API for weather forecasts. My goal is to display specific information for the upcoming 5 days: - Minimum and Maximum temperature for each day - Weather icon - Current weather description (Drizzle, Su ...

How can I correct the code that is running both the if and else statements simultaneously?

In the code snippet below, a comparison is made between a username and password. If both are correct, the user is redirected to another page. However, there seems to be an issue where both the if and else statements are executing. Code: if (isset($_POST[ ...