Tips for activating the Enter key press event when the URL hash is modified

Check out the sandbox here.

I've neatly organized my links inside <li> elements. Whenever a link is clicked, the URL of the page changes to the corresponding <div> id element on the page.

Currently, I'm trying to figure out how to simulate the enter key press event in the makeIt() function so that it automatically scrolls to the related <div> element.

Take a look at my code:

<template>
<div>
  <div style="margin-top: 50px;"></div>
  <div style="margin-bottom: 50px;">
    <ul>
      <li
        v-for="i in 3"
        :key="i"
        @click="makeIt(i)"
      >
        Link{{ i }}
      </li>
    </ul>
  </div>
  <div
    v-for="i in 3"
    :id="i"
    :class="`div${i}`"
    >
    Div {{ i }}
  </div>
</div>
</template>

<script>

export default {
  methods: {
    makeIt(hashbang) {
      this.$router.push(`#${hashbang}`)
    }
  }
}
</script>

<style>
.div1 {
    background-color: red;
    height: 600px;
}

.div2 {
    background-color: blue;
    height: 500px;
}

.div3 {
    background-color: yellow;
    height: 500px;
}
</style>

Any suggestions on how I can achieve this objective?

Answer №1

If you want to modify the behavior of your makeIt function in your template, you can pass the $event object like this:

HTML:

@click="makeIt(i, $event)"

JS:

makeIt(hashbang, event) {
if (event.keyCode === 13) {
//perform desired action
}
      this.$router.push(`#${hashbang}`)
    }

Answer №2

There may be a better way to scroll down to the desired section than triggering the Enter keypress.

One option is to use VueScrollTo for handling the scroll functionality. You can find more information about VueScrollTo here. With VueScrollTo, you can easily call VueScrollTo.scrollTo() within the makeIt method.


makeIt(hashbang) {
  this.$router.push(`#${hashbang}`);
  VueScrollTo.scrollTo(`.section-${hashbang}`, 500);
}

Here's a live example of how this could work: jsfiddle.

If you still want to include the index in the URL for direct access to specific sections, consider utilizing the hash property of routes and implementing the scrollBehavior() method in your router configuration as shown below:

Instead of using $router.push() and the makeIt() method, you can simplify the process by setting up your router links like this:

<router-link tag="li" v-for="i in 3" :key="i" :to="{ name: 'theRouteName', hash: '#section-' + i }">Link {{i}}</router-link>

Incorporate the scroll behavior into your router setup:

const router = new VueRouter({
  routes,
  mode: "history",
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    if (to.hash) {
      return { selector: to.hash };
    }
    return { x: 0, y: 0 };
  }
});

You can test out this approach using the version provided on jsfiddle. Feel free to experiment with it in your environment or local development setup.

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

What is the process for importing a sprite sheet along with its JSON file into my Phaser game?

Currently, I am in the process of developing a game using the powerful phaser game engine. To enhance the visual appeal of my game, I decided to create a sprite sheet and successfully downloaded it. The sprite sheet consists of a 256 × 384 .png file ...

Verify the data type of the returned information from the graphql query

Within my code, I am utilizing a graphql query through a hook that has been automatically generated by Codegen. Codegen not only creates return types but also all data types required. According to the types defined by codegen, the expected return type of m ...

The contents of a Javascript array are not appearing within a div element

I have developed a program that reads JSON data related to a concert event. The JSON file consists of an object named global, which includes details about the band name and venue. Additionally, there is a tickets object that contains information on all ava ...

The MDL layout spacer is pushing the content to the following line

Here's an interesting approach to Material Design Lite. In this example from the MDL site, notice how the 'mdl-layout-spacer' class positions elements to the right of the containing div, giving a clean layout: Check it out <!-- Event ca ...

Challenges encountered when attempting to align faces within Three.JS stemming from the use of two distinct

I'm currently facing an issue with my three.js code. My goal is to align two objects by selecting two faces and rotating the second face (and object) to match the normal vector of the first object's selected face. Here is what I have so far: v ...

Arranging an array of JSON objects based on a chosen key

I'm currently utilizing Nuxt.js, which is built on Vuejs 2. Below is the data I am working with: nodes: {}, models: [ { id: 1, name: "samsung", node: 1, price: 56 }, { id: 1, name: "samsung", node: 2, price: 68 }, { id: 2, na ...

Tips on deleting a range of numbers in a list with jquery

I currently have the following layout: <ul id="ip-top-menu"> <li>Doesn't exclude</li> <li>Doesn't exclude</li> <li> <span>Doesn't exclude</span> <ul> ...

Mongodb: Search for IDs within a nested array field

My MongoDB data structure includes user profiles with friend request information. Here's an example: { _id: "someId", profile: { username: "oliv", friendRequests: [ { fromUserId: "anId", accepted: false, created: " ...

Indeed, yet another problem with clearInterval

I could use some assistance as I am currently stuck trying to figure out why the stopTimer() function is not working correctly. Any guidance or suggestions would be highly appreciated. Thank you! http://jsfiddle.net/4Efbd/1/ var counter; function endTim ...

Is it possible to utilize a library function without needing to invoke the 'this' keyword?

Is it possible to call .size(x) without calling .size() if lodash is imported in 'main.js' and used in my component? I've received advice to import lodash in my component, but I prefer a method that works across all components. Appreciate a ...

Error in vue.js: Cannot access property '$forContext' of null object

I have come across a peculiar issue. Despite everything appearing to function correctly, when I submit inputs (whether using the form submit event with a <form/> element or the keyop.enter event), I encounter the following error in my JS console that ...

How to open a link in the URL bar of Safari on iOS using JavaScript

My goal is to open a link through the iOS Safari address or URL bar. After testing, I have found that in newer iOS versions, the address bar no longer executes javascript:alert("hi"); as it did before. Have any new methods been introduced, or h ...

A guide on how to use Javascript to take a screenshot of an entire webpage

When a user triggers a script, it injects JavaScript code into the current page to make DOM changes. After interacting with the page, the user may want to save their modifications for later viewing or editing. However, if the original page source is edited ...

What causes the white screen issue when utilizing Inertia in Laravel for page rendering?

The technologies I'm working with are: Laravel, Inertiajs, and Vue.js. Although I am new to using Laravel, I encountered an issue when running composer require laravel/breeze --dev and php artisan breeze:install vue which resulted in my Laravel proj ...

Incorporating append and clone through a loop with jQuery

Is there a way to properly order div elements generated using .append() and .clone methods in a for loop? Despite creating the initial div before the loop, the order seems to be incorrect. The first div (class news0) is being displayed after the last div ( ...

Conceal the message using star symbols

I need help figuring out how to hide a certain type of string input from the user, and then use Angular data binding to display it in another component with part of the data masked with asterisks. I'm not very skilled in JavaScript, so I'm wonder ...

Tips for embedding Apache Superset visualizations into an Angular 7 app: Overcoming hurdles with authentication and headers

I am currently working with Apache Superset to create charts. I am looking to embed these charts in my Angular 7 application using an iframe. One major problem I encountered is an authentication failure with the following error message: Refused to display ...

Are there any user interface frameworks available that can replicate the aesthetic of a Mac application?

I've been searching high and low but I haven't come across any answers yet. It caught my attention that the wunderlist mac app was developed using HTML/CSS/JS, but I'm curious if they incorporated a pre-existing UI JavaScript framework into ...

Performing multiple AJAX calls from JavaScript

for(var y=0 ; y<=23 ; y++) { AjaxRequest99 = null; AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) { AjaxRequest99.open("GET", "aja ...

The date displayed on the popup calendar is local time, while the date selected is in Coordinated

Is there a way to maintain the selected date in UTC format? I am experiencing an issue where the pop-up calendar does not synchronize with the selected datetime. For instance, when I click on 08/13 and the selected date shows as 08/12. This discrepancy ...