Tips for appending the id of an active element to a URL

My goal was to include the id value of the active element in a URL and then redirect to that URL with a button click.

HTML

<div class="icon" tabindex="0" id="company">
    <img src="company.png">
</div>
<button type="submit" onclick="myFunction()">jump</button>

Javascript

function myFunction(){
   var x = document.activeElement.id;
   location.href = "apps-online.html?page=" + x;
}

When clicking the button, my expectation was to be redirected to:

"apps-online.html?page=company"

However, the url ended up being:

"apps-online.html?page="

I'm puzzled as to why the value of x wasn't added to the url.


Hello everyone. I have now realized why this issue occurred. Each time the button is clicked, it becomes the last active element.

Is there a way to solve this and achieve my desired result?

Answer №1

Make sure to verify the value of x to see if it is empty. If x is empty, then the URL will have no value. Try troubleshooting the code or utilize console.log.

function myFunction(){
   var x = document.activeElement.id;
   console.log(x);
   location.href = "apps-online.html?page=" + x;
}

This will display the value of x in the console for verification purposes.

Answer №2

Looks like your button is missing an id.

Add id="company" to the button element.

<div class="icon" tabindex="0">
  <img src="company.png">
</div>
<button id="company" type="submit" onclick="myFunction()">jump</button>

Answer №3

When you press the button, the highlighted element is the button itself. Let's say you have multiple divs and you want to pass the id of the selected element. There needs to be a way to transfer the id to the function.

Check out the example below for one possible solution.

HTML

<div class="icon" tabindex="0" id="company">
    <img src="company.png">
</div>
<div class="icon" tabindex="1" id="something">
    <img src="something.png">
</div>
<button type="submit" onclick="myFunction()">jump</button>

JS

let tabID = null;
let icons = document.getElementsByClassName('icon');

for (icon of icons) 
{
    icon.onclick = function() 
    {
        tabID = document.activeElement.id;
    }
}

function myFunction()
{
    window.open("apps-online.html?page=" + tabID);
}

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

Utilizing REACT to extract values from deeply nested JSON structures

Currently, I am utilizing react to display information from properties stored in a nested JSON. While I can successfully render properties like 'name' and 'id' that are not nested, I encounter an issue when trying to access a nested pro ...

"Clicking on the 'View More' button within a foreach loop is only functional for the

I am trying to iterate through a list of items using a foreach loop, and each item has a "view more" option. The intention is that when I click on this option, it should expand to show more details about the respective item. However, I am encountering an i ...

QuickCopy - Capture only what's in view

Hi there, I have a question: I'm trying to figure out how to make a button copy only the visible text within the element with id="description". Can someone help me troubleshoot? HTML: <p id="description"> Test <span style="display:none"> ...

What is causing the width discrepancy in my header section on mobile devices?

Help needed with website responsiveness issue! The site works fine on most screen sizes, but when it reaches around 414px in width, the intro section becomes too wide for the screen. Any ideas on what could be causing this problem? html: <nav id="m ...

Creating a unique seal, badge, or widget in Django is a fun and rewarding project

Here are some examples of what I want to accomplish: View the gif showcasing the function Visit https://sectigo.com/trust-seal Check out another gif demonstrating the function Explore https://www.carandtruckremotes.com/ Don't miss this gif showin ...

Creating dynamic pagination in React using a variable length loop

I'm currently implementing pagination using react ultimate pagination. When a page number is clicked, I update a variable to display the necessary content. The challenge arises from having a loop with a variable number of elements, making it impossibl ...

"Maximizing Efficiency: Chaining Several Actions Using the JavaScript Ternary Operator

When the condition is true, how can I chain two operations together? a = 96 c = 0 a > 50 ? c += 1 && console.log('passed') : console.log('try more') I attempted chaining with && and it successfully worked in react, b ...

"Incorporate multiple data entries into a table with the help of Jquery

How can I store multiple values in a table row using jQuery or JavaScript when the values come from a database via Ajax? <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th ...

Is there a way to properly dissect or iterate through this?

I have exhausted all possible methods to retrieve the data, but I am unable to solve this puzzle. The information is organized in a format like the following: [{"code":1000,"day":"Sunny","night":"Clear","icon":113,"languages": [{"lang_name":"Arabic","lan ...

Tips on converting deeply nested JSON into an excel file using Node.js

I am attempting to convert the JSON data below into an Excel file using XLSX. Although it successfully converts my JSON to Excel, I encountered an issue where the nested array of dailyPointsArray appears blank after conversion. Code Attempted const XLSX ...

Is there a way to retrieve MongoDB count results in Node.js using a callback function?

Is there a way to access mongodb count results in nodejs so that the outcome can be easily retrieved by asynchronous requests? Currently, I am able to retrieve the result and update the database successfully. However, when it comes to accessing the varia ...

Placing a pseudoelement amidst the track and thumb of a range input type

I'm trying to position a pseudo element with a specific z index that is lower than the thumb of an input type range but higher than its track. This is what I have so far: HTML: <div class="range"> <input type="range" name="" class="progre ...

Prevent lengthy headers from disrupting the flow of the list items

I've encountered an issue while working on a website that features a list of items. When the title, such as "roller blinds," spans across two lines, it disrupts the layout below. How can I prevent this from happening without compromising on having lon ...

Utilize the inverse mapping method along with conditional statements inside a mapping function

When looping through the categories using categories.map(), I am trying to reverse the elements of the categories and also check for category.isFeatured before creating a link. However, I am unable to use an if statement in this scenario. const Header = ...

Add a plethora of images to the canvas

Just starting out with Fabric.js and trying to figure out how to draw a picture on the canvas after a drop event. I managed to do it once, but am struggling with inserting more pictures onto the canvas (each new drop event replaces the previous picture). ...

Testing a React component's function within the confines of a Redux Provider component

My current challenge involves unit-testing a React component called TodoList. This component essentially maps through items and displays them in the render method. These items, of type TodoItem, are retrieved from the Redux store using MapStateToProps. Be ...

Discovering the geometric boundaries of a body of text

Seeking help with determining the geometric bounds of text inside hyperlinks in an InDesign document. I've tried to do this using ExtendScript but haven't had any luck. // Loop through and export hyperlinks in the document for (k = 0; k < myD ...

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

What's the best way to unpack the gzip data that Ajax sends to JavaScript?

Hello there! I've encountered an issue: PHP is sending compressed data using gzdeflate(): $string=gzdeflate($string,9); echo $string; In the browser, pako.js has been included and the following code is executed: var rsp=rst.responseText; rsp=pako.in ...

Combining Laravel with React

Currently in the process of developing a substantial real estate listings platform with react and laravel. Can you suggest which approach would be better for this project and explain why? Option 1: Implement laravel react presets and store all react compo ...