Replace the anchor tags with a JavaScript array

Looking to replace a simple anchor link with JavaScript array code. We're taking the long route here, and it's not as straightforward as we thought. The scrollTo property isn't working for us; can anyone spot where we might be going wrong?

Here's the snippet of JavaScript:

$(function(){
    //Search index for Cards
    var gameA = new Array('normal','ex','promo','counterfeit');

    $('#go').click(function(e){
        var term = $('#term').val();
        var searchIndex = gameA.indexOf(term);
        console.log(term);
        console.log(searchIndex);
        if (searchIndex > -1){
            console.log("hi");
            window.scrollTo(0,"#sec"+searchIndex);
        } 
    });
});

And this is the source code in question:

<h2 id="top">Select a Term</h2>
<p>List: Normal, Ex, Promo, Counterfeit</p>
<form action="javascript:void(0)">
<label for"term">Enter a term from the list above.</label><br>
<input type="text" id="term" name="term">
<button id="go">Go</button>
</form>
</div>

<!-- More elements below -->

<br><br>
<img src="images/fancycards.jpg" width="1191" height="670" alt="fancy cards"><br>

<h2 id="sec0">Normal Cards</h2>
<p><a href="#top">Back to Top</a></p>
<img src="images/cards.jpg" width="1131" height="707" alt="cards"><br>

<h2 id="sec1">Ex Cards</h2>
<p></p>
<img src="images/excards.jpg" width="1000" height="653" alt="ex cards"><br>

Answer №1

From what I've found, it seems that window.scrollTo requires coordinates as arguments rather than an element's ID.

Instead of using your current scrollTo command, you can try the following snippet:

window.scrollTo(0, $("#sec"+searchIndex).offset().top)

I've provided a JSFiddle demo with this adjustment. Keep in mind that the images may not display, but the scrolling functionality should work correctly: http://jsfiddle.net/1mpqm1te/2/

Answer №2

In order to use the scrollTo() function correctly, make sure you pass a number instead of a string. The number should represent the Y offset of the element you wish to scroll to. One way to achieve this is by assigning semantic ID values ('normal-cards', 'ex-cards', etc) to the card sections.

http://jsfiddle.net/yLvhh53a/

$(function () {
    //Search index for Cards
    var gameA = new Array('normal', 'ex', 'promo', 'counterfeit');

    $('#go').click(function (e) {
        var term = $('#term').val();
        console.log(term);
        var item = $('#' + term + '-cards');
        console.log(item);
        
        $('html, body').animate({
            scrollTop: item.offset().top
        }, 1000);


    });

});
<h2 id="top">Select a Term</h2>

<p>List: Normal, Ex, Promo, Counterfeit</p>
<form action="javascript:void(0)">
    <label for "term">Enter a term from the list above.</label>
    <br>
    <input type="text" id="term" name="term">
    <button id="go">Go</button>
</form>
</div>
<br>
<br>
<img src="images/fancycards.jpg" width="1191" height="670" alt="fancy cards">
<br>

<h2 id="normal-cards">Normal Cards</h2>

<p><a href="#top">Back to Top</a>
</p>
<img src="images/cards.jpg" width="1131" height="707" alt="cards">
<br>

<h2 id="ex-cards">Ex Cards</h2>

<p></p>
<img src="images/excards.jpg" width="1000" height="653" alt="ex cards">
<br>

By using consistent IDs like '[name]-cards' for each section added, there is no need to reference an array. The script will automatically locate the designated section. Additionally, you have the option to adjust the scroll speed as desired.

Answer №3

To navigate to a specific element on a webpage by its id, you can easily update the hash in the URL.

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

Determining height of an element in AngularJS directive prior to rendering the view

As I dive into the world of Angular, any assistance is greatly welcomed. My goal is to vertically align a div based on screen size (excluding the header and footer) when the page loads, the window resizes, and during a custom event triggered by the user ex ...

Is it possible for a Simplemodal popup to appear only once per user session

I'm completely new to javascript and jQuery. Recently, I've started using SimpleModal basic from SimpleModal to show a popup upon visitors landing on my website. Everything seems to be working perfectly, but there's one issue - the popup kee ...

JavaScript Tip: Effortless method to confirm the presence of duplicate values within an array

Similar Question: Best method for identifying duplicate values in a JavaScript array If I have an extensive array containing thousands of elements, I am looking to check if there are 2 or more elements with identical values and return true. I unders ...

Calculating the time difference in days, hours, minutes, and seconds between two UNIX timestamps

I have a special occasion coming up, and the date and time for this event are stored in a Unix timestamp format. Instead of relying on a plugin like modern.js, I am trying to figure out the time difference between today's date and the event date usin ...

Configuring timezone for 'date' type in Plotly.js

I'm currently working on a graph to showcase the trend over time. The data I have is in Unix format and I use JavaScript code (new Date(data)).toUTCString to display it in my title. Surprisingly, while the data for the graph and the title is the same, ...

Performing additions on two-dimensional arrays using Angular/JavaScript

Currently, I am in the process of learning basic JavaScript and could use some assistance. My task involves working with two-dimensional arrays where the 0th index will always represent a date and the 1st index will always be an integer in the array. My go ...

Angular Igx-calendar User Interface Component

I need assistance with implementing a form that includes a calendar for users to select specific dates. Below is the code snippet: Here is the HTML component file (about.component.html): <form [formGroup]="angForm" class="form-element"> <d ...

How to Set Up a Simple Gulp Uglify Configuration

My objective is to compress all .js files within my project and save a minified version in the same directory. Assuming this is the structure of my project directory: project/ gulpfile.js basic.js Project/ Project.js Toolbelt. ...

Cleaning up React async functions using hooks for fetching data

This code snippet is from a functional component. Within this component, there is a submit() function that handles form submission: async function handleSubmit(event) { event.preventDefault(); try { let resp = await fetch("FOOBAR/BAX", { ...

Populate a byte array of a specified size using a generator

Starting from a previously calculated very long array of small bytesize numbers (MB, GB, TB) in a bytearray, I must calculate a subsequent bytearray in the next iteration. I can determine the necessary size for the next iteration's bytearray in advanc ...

The useEffect hook is activated whenever any function within the component is executed

After extensive research, I have not been able to find a solution to my question. Any help would be greatly appreciated. This code snippet represents a functional component that deals with state and props: // blog id const { id } = props.match.params; // ...

Are the new node buffers already populated with information?

Is this a node bug or is it the expected behavior? This issue can be reproduced in versions 0.12.7 and io 3.1.0: > new Buffer(5) <Buffer 00 00 02 00 00> > new Buffer(5) <Buffer 00 00 00 00 00> > new Buffer(5) <Buffer 28 94 00 02 ...

Understanding the process of extracting elements from a list in Python

I extracted some data from a function and now I'm trying to extract specific information like the shape, labels, and domain from this output. [Annotation(shape=Rectangle(x=0.0, y=0.0, width=1.0, height=1.0), labels=[ScoredLabel(62282a1dc79ed6743e731b3 ...

Guide on creating a conditional column in a kendo UI grid with the use of AngularJS

Is there a way to dynamically add a column to the Kendo UI grid based on JSON data? Consider the following JSON input: [{ "ProductID": 1, "ProductName": "Chai", "Supplier": { "SupplierID": 1, "SupplierName": "Exotic Liquid ...

Error: Express is undefined and does not have a property called 'use'

I'm encountering a problem with my express server specifically when I utilize the 'app.use' command. Within my task-routes.js file, the following code is present: import express from 'express'; const router = express.Router(); ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

What might be causing the sudden shifts in element positions during TweenLite animation?

I have created a demo of my code in this JSFiddle and also included it below. The issue I am facing occurs in Google Chrome, so I would recommend using that browser to replicate and fix the bug. Please note that the code is a snippet from a larger project ...

Modifying the row background in a DataTables drawCallback

Is there a way to dynamically change the background color of a row based on a specific value in a cell using drawCallback? $(table_id).DataTable({ //... "drawCallback": function (settings) { // Here, if the type of data in a particular ce ...

The footer section of my website seems to have gone missing in the HTML/CSS coding

I'm having trouble with my website footer not displaying. I've tried using "position: absolute; top: 50px; left:100px;" in my HTML/CSS, but it's not working. Can anyone help me fix this issue? Here is a link to the code I'm working on: ...

Angular Ionic: Unable to compare 'value'. Only arrays and iterable objects are permitted for differentiation

I attempted to display a list value and when I logged the value of the list, it appeared exactly how I wanted: unit value {id: 81, name: "3 BR Suite"} unit value {id: 82, name: "3 BR Grande"} unit value {id: 83, name: "Pool Villa&q ...