Is there a way to identify if an element has been clicked using jQuery upon initial page load?

Currently, I am attempting to assign a javascript variable to one of several possibilities.

If a specific link has not been clicked (such as on the initial page load), then the variable should default to 0 or 1.

However, if one of those links has been clicked, I want the variable to receive the number associated with that particular link.

Imagine the HTML structure is like this:

<a href=""><img src="icon2.png" id="icon-2"></a> |
<a href=""><img src="icon3.png" id="icon-3"></a> |
<a href=""><img src="icon4.png" id="icon-4"></a> |

In jQuery, the variable setup could look something like this:

var icon_num = 2; // This will change based on which 'icon' is clicked.

Answer №1

One way to achieve this functionality is by implementing the following approach:

let current_icon = 0;
$("#container img").click(function() {
  current_icon = parseInt(this.id.replace("icon-",""), 10);
});

Alternatively, you could assign a data attribute containing only the ID like so:

<img src="icon3.png" data-id="3" />

By utilizing this method, your code can be streamlined as follows:

let current_icon = 0;
$("#container img").click(function() {
  current_icon = parseInt($(this).attr("data-id"), 10);
});

Answer №2

Click here for an illustrative example

let selected_icon = null;  // no icon selected initially

$('a').bind('click', function(e) {

   e.stopPropagation();

   selected_icon = $(this).find('>img').attr('id').split('-')[1];

   return false;

});

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

Initiating an audio call exclusively via SimpleWebRTC

I'm currently utilizing a jQuery plugin for WebRTC found here. My goal is to initiate an audio call only, but I am struggling to find a function within the plugin that allows for this. The code snippet I am using with autoRequestMedia set to false is ...

Filtering data in AngularJS by parsing JSON records

I have a JSON file containing restaurant information and I need to display the data by grouping them based on their respective address fields. For example, all restaurants with the address 'Delhi' should be shown first, followed by those from &ap ...

Retrieving the $scope data from within an http.get callback

Would someone be able to assist me with storing the data returned by the $http.get function in a $scope variable for use in my ui-grid control? I have tried the code below but seem to be missing something simple. I just can't figure out what it is: ...

Enhance the appearance of the standard black rectangle displaying the messages "No video source" or "No video permissions"

Is there a way to change the styling of the video element that appears as a black rectangle with a strikethrough play button when the user is prompted for permission on Safari? Does it have a specific ID, class, or tag that can be targeted? I'm curre ...

What is the best way to submit a form inside a Bootstrap (4) modal that only contains hidden inputs when pressing the enter key?

I have set up a form within a Bootstrap modal that contains hidden inputs and a concealed submit button. The goal is for the user to click a button, open the modal, and then press the enter key to automatically submit the form. Through my research and tes ...

Creating a fading header effect with a gradual transition as it disappears

I'm working on a header that should disappear when the user scrolls down and reappear when scrolling back up. I've managed to make the header reappear with a smooth transition, but the disappearing effect is instant, which is not what I want. I n ...

Can you explain the difference between a public app and express.Application?

As I delved into the world of TypeScript and Node, I stumbled upon a perplexing line of code: public app: express.Application; This line is nested within the context of an import statement and a class definition. Let's take a closer look at it: i ...

Tips for customizing the appearance of a specific cell in the first column of a Material UI table

Currently, I am modifying the material ui table found in this codesandbox link. My goal is to adjust the style of the first column's cell in the table when it is selected to match the image provided below. https://i.sstatic.net/DGubN.png It seems lik ...

Text width that adjusts dynamically

Consider this HTML structure; <div> <span>Text one</span> <span class="sticky">ABC</span> </div> <div> <span>Some other text</span> <span class="sticky">DEF</span> </div> < ...

Enhance User Experience with jQuery Toggle Feature

Below is the code snippet that I am currently working on: $(document).ready(function() { // Manage sidebar category display jQuery("#categories > ul > li.cat-item").each(function(){ var item; if ( jQuery(this).has("ul").length ) { ...

Changing the Row's Background Color in Angular When the Button is Clicked

My code includes a list where each row has a button to open a sidebar. Due to the large number of elements in the list, I want the background color of the row to turn yellow when the button is clicked, as a way to indicate what has been selected. Currently ...

Ways to eliminate the gap between the currency symbol and the numerical value in HTML

Is there a way to eliminate the gap between the Currency Symbol and Amount? I've been attempting to get rid of the space between the currency symbol and the amount in my HTML code. However, even when I input decimals, there remains a gap between the ...

Looped jQuery setTimeout not functioning correctly

I am facing an issue with processing a JSON file that contains a list of serialized objects. My goal is to walk through this JSON and display the messages from it one at a time, with a delay of 2 seconds between each message before ultimately stopping. I a ...

Calculate the number of input boxes that have been filled

<input type="number" name="day1"> <input type="number" name="day2"> <input type="number" name="day3> Can anyone help me figure out how to count the number of filled fields in this form? For example, if only day1 is filled, the count resu ...

Obtain appended data from the formData

After creating a new FormData object and adding 'caption' as the key, how can I retrieve the value 'abc'? Using the .get method doesn't work in mobile Chrome due to lack of support. Is there an alternative method to get the caption ...

How can I construct a frame-like structure using PHP and HTML?

Looking to create a page with a two-frame structure. The left frame will always display a small form with 10 entries that, upon submission, trigger some processing and display results. The left frame must remain accessible at all times, while the right fra ...

I can't figure out why I'm receiving undefined even though all the variables are populated with the necessary

I have been working on a project that involves implementing email and password authentication using Firebase. However, I encountered an error when the user submits their credentials: FirebaseError: Firebase: Error (auth/admin-restricted-operation). at ...

Tips for properly implementing ng-hide and ng-show across various sections of your single page application

Currently working on a Single Page Application (SPA). I've included some buttons in the side navigation with the intention of displaying different content when they are clicked. However, I encountered an issue where using ng-hide and show didn't ...

Can you please explain the significance of the code "!!~this.roles.indexOf('*')" within the MEAN.io framework?

One particular line of code can be found in the startup file for the MEAN framework. if (!!~this.roles.indexOf('*')) { This specific line is located within the shouldRender function of the menus.client.service.js file, which resides in the publ ...

Deactivating upcoming weeks according to the year in Angular 8

In the user interface, there are dropdowns for selecting a year and a week. Once a year is selected, the list of weeks for that year is displayed in the week dropdown. Now, the requirement is to disable the selection of future weeks. For example, for the ...