Use href id to navigate back to the top of the page by

I am trying to implement a function that scrolls the div to the top position. However, I am encountering an issue with retrieving the href value. When I use 'a' in console.log(a);, it returns undefined.

function myFunction()
   {
      var a=$(this).attr('href');
  console.log(a);
  $('html, body').animate({scrollTop: $('#'+a).offset().top-40}, 500);
 }
#consulting,#segments,#partner,#insights{min-height:100vh;}
   .secMenu{position:fixed;
   }
<div class="container-fluid">
  <div class="row secMenu">
<div class="col-md-9 col-sm-12 menu">
 <ul class="nav navMenu">
 
  <li class="test1"><a href="#consulting" onclick="myFunction()">Consulting & Solutions</a></li>
  <li class="test2"><a href="#segments"  onclick="myFunction()">Segments</a></li>
  <li class="test3"><a href="#partner"  onclick="myFunction()">Our Partners</a></li>
  <li class="test4"><a href="#insights"  onclick="myFunction()">Perspectives</a></li>
</ul>  
</div>

   </div>   <!--End of second menu -->
    <div class="row">
   <div id="consulting">
   div1
</div>
<div id="segments">
div11
</div>
<div id="partner">
div111
</div>
<div id="insights">
 div1111
</div>
</div>
  </div>

Answer №1

I have created a different approach than what you initially used, but the outcome remains the same. I opted to eliminate the function previously utilized and instead incorporated jQuery. Hopefully, my solution meets your requirements:

$('.nav li a').on('click', function(e) {
  e.preventDefault();
  var a = $(this).attr('href');
  $('html, body').animate({
    scrollTop: $(a).offset().top
  }, 500);
});
#consulting,
#segments,
#partner,
#insights {
  min-height: 100vh;
}
.secMenu {
  position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
  <div class="row secMenu">
    <div class="col-md-9 col-sm-12 menu">
      <ul class="nav navMenu">

        <li class="test1"><a href="#consulting">Consulting & Solutions</a>
        </li>
        <li class="test2"><a href="#segments">Segments</a>
        </li>
        <li class="test3"><a href="#partner">Our Partners</a>
        </li>
        <li class="test4"><a href="#insights">Perspectives</a>
        </li>
      </ul>
    </div>

  </div>
  <!--End of second menu -->
  <div class="row">
    <div id="consulting">
      div1
    </div>
    <div id="segments">
      div11
    </div>
    <div id="partner">
      div111
    </div>
    <div id="insights">
      div1111
    </div>
  </div>
</div>

To view the implementation in action, you can click on the Run code snippet button above or explore a fiddle here.

Answer №2

Since this is automatically linked to the global object (such as window in a browser), you may need to explicitly pass it to the function.

To achieve this, you can pass this as an argument to myFunction() like so: myFunction(this). In the definition of myFunction:

function myFunction(target) {...}
, the parameter target will now represent the anchor element being referenced.

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

Creating a three.js lathe object using SVG spline with a Bézier curve

For my new game project, I am currently designing a replica of the iconic theme building located at LAX airport. I am exploring methods to transform an svg spline (featuring Bézier curves) into a lathe object within three.js. Is there a reliable way to a ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

Tips for adjusting the transition speed duration in Bootstrap 4

Is there a way to enhance the smoothness of image slides? I can adjust the speed between slides using data-interval, but how do you tweak the speed within each slide? According to the documentation: .carousel-item{ transition: transform 5s ease, opacit ...

Is it possible to achieve the lower link set in a pure CSS horizontal menu where the horizontal link set is positioned below horizontal text tabs?

I am attempting to design a pure CSS on-hover horizontal menu. I have made some progress on my design, as shown in http://jsfiddle.net/dq8z192L/11/ The goal is to have a menu that expands horizontally when hovered over. Each tab reveals a set of links be ...

Is there a way to verify that only the image was uploaded?

// why isn't this code working when I upload 1.chicken.jpg with a size of 180kb and 2.chicken.pdf, but only the chicken.pdf file gets inserted into the database? HttpFileCollection hfc = Request.Files; if (hfc != null) ...

Tips for inserting the <a> HTML tag into a JSON array object

I am relatively new to creating array objects and I am unsure on how to add a link within a <a> tag in a JSON file. Here is the JSON object code: powerUpList: [ { id: 8, name: 'Automate your API column type ', description: & ...

Sorting through nested objects on the client sideorFiltering

I have a d3.js scatterplot based off of this: http://bl.ocks.org/nsonnad/4481531 I'm attempting to implement a feature that enables filtering based on different criteria, such as country in the provided example (each represented by a color bubble). ...

Verify the status of the checkbox to determine if the user has enabled or disabled

To check the condition based on whether a user is enabled or not, I have implemented a checkbox feature. By default, the checkbox is checked, signifying that the user is enabled. However, if the user wishes to update their status, they can simply click on ...

Exploring IdentityServer3: A Deep Dive into OAuth Flows and Varied Strategies

After developing a REST Web API application, I want to provide other developers with the capability to access those APIs on behalf of the user. To achieve this, I have implemented OAuth authentication with IdentityServer3. Currently, I have successfully ge ...

Enhance with Laravel combined with AngularJS

I've encountered some issues with the "edit" part while working on a Laravel + AngularJS CRUD application. An internal server error is being displayed, and I'm seeking assistance to understand its cause. Error "GET localhost/crudtcc/public/ap ...

The functionality of jQuery to carry out an action via AJAX prior to form submission is not functioning

My goal is to save data to the database using AJAX when a form is submitted, and then proceed with submitting the form to PayPal. However, after saving the data successfully in the database, the form does not continue further. $('#saveBeforePay' ...

Unlimited Page Scrolling with Functional Browser Back Button using jQuery

My e-commerce website features an infinite scroll function that works smoothly. However, there's an issue with the back button functionality for customers previewing products - they have to start over when navigating back on pages with 100+ products. ...

axios error: Trying to access 'slice' property of null object

Encountered an error while implementing server-side rendering with Redux in React Error Details: TypeError: Cannot read property 'slice' of null at dispatchHttpRequest (E:\Projects\real-estate\node_modules\axios\li ...

Encountering a CouchDB 401 Unauthorized Error

I have a couchDB database named "guestbook". Initially, I utilized the following code to add a user to the "_users" database: $scope.submit = function(){ var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name; console.log(url); $ht ...

A custom ASP MVC form that triggers a specific action without redirecting, instead updating the original page

As I delve into using ASP.net MVC 3 for my project, I find myself comparing it to the familiar WebForms world that I have been accustomed to for so long. In WebForms, handling a postback was as simple as placing fields on the form, adding a button, creatin ...

Navigating through the endless scroll behavior in Twitter using CasperJS (PhantomJS)

Having trouble with infinite scrolling on Twitter, as the page is not loading new content even when scrolling to the bottom. To test if any content loads at all, I have used the following code snippet: casper.open('https://twitter.com/<account> ...

Obtain the value of an element from the Ajax response

Just starting out with Jquery and Ajax calls - here's what I've got: $(document).ready(function () { $.ajax({ type: "GET", url: "some url", success: function(response){ console.log(response); } }) }); Here's the ...

Using 2 viewports depending on the device

My website looks great on all devices and desktop, but I want to set a different viewport for iPad. I would like the iPad to have the same width as my desktop version, which is 1100px wide. Currently, the site is designed with percentages and ems up to (ma ...

Can the TEXT from a <select> be passed as the value of a hidden <input> element?

<form method="POST" action="question-function.php"> <label>Choose Category</label> <select name="catid" id="catid" class="form-control"> <?php $sel3 = mysqli_query($ ...

Reduce the spacing between div elements to eliminate any gap between the rows

I'm trying to keep the divs close together, but the second row isn't lining up properly and the divs don't have any margin. My CSS for the div is as follows: .post { box-sizing: border-box; display: block; float: left; font ...