Tips for choosing an <li> element with JavaScript

<style>
     .sys_spec_text{}
     .sys_spec_text li{ float:left; height:28px; position:relative; margin:2px 6px 2px 0; outline:none;}
     .sys_spec_text li a{ color: #db0401; height:24px; padding:1px 6px; border:1px solid #ccc; background:#fff; display:inline-block; line-height:24px;}
     .sys_spec_text li a:hover{ border:2px solid #e4393c; padding:0 5px; text-decoration:none;}
     .sys_spec_text li i{ position:absolute; width:10px; height:10px; font-size:0; line-height:0; right:2px; bottom:2px; background:url(img/sys_item_selected.gif) no-repeat right bottom; z-index:99; display:none;}
     .sys_spec_text li.selected a{ border:2px solid #e4393c; padding:0 5px;}
    .sys_spec_text li.selected i{ display:block;}
</style>


<ul class="sys_spec_text">
    <li ><a href="javascript:;" title="xl">xl</a><i></i></li>
    <li ><a href="javascript:;" title="l">l</a><i></i></li>
</ul>

When the user manually clicks with a mouse, the li border turns red. How can this be achieved automatically using JavaScript?

Answer №1

This code snippet accomplishes your desired outcome.

To implement this functionality, first define the CSS style for .clicked with a red border.

Next, in JavaScript, set up event listeners to detect clicks and then add the clicked class to the clicked element.

document.querySelectorAll("li").forEach(li => {
   li.addEventListener("click", function(event)  {
       event.target.classList.add("clicked");
   });
});
<style>
    .sys_spec_text{}
    .sys_spec_text li{ float:left; height:28px; position:relative; margin:2px 6px 2px 0; outline:none;}
    .sys_spec_text li a{ color: #db0401; height:24px; padding:1px 6px; border:1px solid #ccc; background:#fff; display:inline-block; line-height:24px;}
    .sys_spec_text li a:hover,
    .sys_spec_text li .clicked { border:2px solid #e4393c; padding:0 5px; text-decoration:none;}
    .sys_spec_text li i{ position:absolute; width:10px; height:10px; font-size:0; line-height:0; right:2px; bottom:2px; background:url(img/sys_item_selected.gif) no-repeat right bottom; z-index:99; display:none;}
    .sys_spec_text li.selected a{ border:2px solid #e4393c; padding:0 5px;}
    .sys_spec_text li.selected i{ display:block;}
</style>
<ul class="sys_spec_text">
    <li ><a href="javascript:;" title="xl">xl</a><i></i></li>
    <li ><a href="javascript:;" title="l">l</a><i></i></li>
</ul>

Answer №2

It would be helpful to clarify the process further. Based on the CSS, you currently display a border when an li element is hovered over. However, you are now inquiring about achieving the same effect but triggered by a click event. This could lead to a scenario where an element retains its border after clicking, as there is no event set up to remove it.

One approach you can take is utilizing the :active pseudo-class for anchor elements, which mirrors the behavior of a click JavaScript event.

If your goal is to mimic a hover event using Javascript, you can listen for 'mouseenter'/'mouseleave' events to replicate the functionality implemented with CSS.

Answer №3

Employ the setInterval() function to periodically monitor and trigger the event as needed.

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

Ways to detect the use of vue.js on a webpage without relying on vue-devtools

One way to determine if the page is utilizing Angular or AngularJS is by inspecting window.ng and window.angular. Is there a similar method to identify whether Vue is being used on the page directly from the console, without relying on vue-devtools? ...

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...

What is the reason behind HTML5 Canvas drawing layering a fresh path onto the current path with each new point added?

Trying to explain the issue is a bit challenging, which is why I created a JS Fiddle to demonstrate what's happening: http://jsfiddle.net/dGdxS/ - (Only compatible with Webkit browsers) When you hover over the canvas, you can draw, but you may need to ...

Issue occurred while executing maildev - logger.info(`Shutdown signal received, beginning shutdown now...`)

After rebooting my machine, I encountered an error when running the maildev command in the terminal. Despite uninstalling and reinstalling the program, the issue persists. Below is the complete error message. Appreciate any help in solving this problem. ...

Tips on effectively utilizing dynamic data with Google Charts

I am working on creating a dynamic chart using Google Charts with multiple CSV files. I want to display a different chart depending on the selection made by the user. The first file loads successfully and displays a chart, but the $("#selection").change(.. ...

Creating a responsive container in Bootstrap that adjusts height dynamically, featuring a text input box positioned at the bottom

I am currently using Bootstrap 4 to design a desktop chatbot inspired by Google's Bard. My goal is to have a container that spans the height of the screen, with the text input located at the bottom of the container. Additionally, I want the container ...

Reduce the amount of times append is used in JQuery

Whenever I click the button in Jquery, I aim to limit the number of appends that occur. function standardRoom() { var counter = 0; if ($('select#selectBoxStandard option').length > 1) { counter++; $('#selectBoxStandard&ap ...

What is the best way to format this <li> element so that the second line of text starts directly below the beginning of the first line, rather than below the bullet point itself?

Is there a way to align the second row of a list item directly below the text and not below the bullet point? <ul class="arrow-list"> <li>Clear and consistent brand identity</li> <li>+47.08% Increase in website registration ...

Sending a JSON array in an AJAX request results in receiving null values in an MVC application

I've been trying to send an array of JSON objects to my controller action, but it keeps showing up as null. Here's the JavaScript code I'm using: function UpdateSelected() { var items = {}; //Loop through grid / sub grids and crea ...

Ways to customize the default CSS styles of angularJS for elements like search box and more

Looking for a way to customize the appearance of an AngularJs search box? <div ng-controller="PersonListCtrl"> <div class="bar">Search: <input ng-model="query"> </div> <ul cl ...

Navigating through events with jQuery

Currently, I am utilizing jQuery Steps and aiming to manage an event known as: onStepChanging. The default value for this event is function (event, currentIndex, newIndex) { return true; } I have attempted the following code snippet, but unfortunately, i ...

What could be causing the redirection to my php file in this particular contact form?

I have a contact form on my website that uses AJAX for submission. Everything seems to be working fine, but when the user clicks on the Submit button, they are redirected to the PHP file instead of staying on the page to see success or error messages. I wa ...

Incorporating Stripe into your Next.js 13 application: A step-by-step guide

Struggling to incorporate Stripe into my Next.js 13 app for a pre-built checkout form. So far, all attempts have fallen short. Seeking assistance from anyone who has conquered this integration successfully. Any tips or guidance would be highly valued. Pl ...

Each time the Jquery callback function is executed, it will return just once

Whenever a user clicks on the "customize" link, I trigger a function to open a dialog box. This function includes a callback that returns an object when the user clicks "save". The problem is, each time the user clicks "customize", the object gets returned ...

Child component not displaying React props (although I can identify them in debug mode)

Currently, I am working on a React project that does not involve Redux. However, I am encountering some difficulties in passing the state from the parent component to the child component. Despite watching numerous tutorials and extensively using the Chrome ...

When I expand the accordion next to it, the accordion disappears, and it also vanishes when I close that accordion

After incorporating accordions into my site, I encountered a peculiar issue (as shown in this video): when I open one accordion, the adjacent accordion also opens unexpectedly. Similarly, closing one accordion causes its neighboring accordion to mysterious ...

Trouble encountered while setting up Firebase Auth for React Native by utilizing AsyncStorage

Trying to implement SMS authentication via Firebase has presented some challenges for me. Despite poring over the documentation and scouring Google for solutions, I've hit a dead end. My setup is pretty basic - just a single input field and a "Send" b ...

Turn off escape option when PointerLockControls are in use

Is there a way to prevent the ESCAPE option from being activated (when using PointerLockControls and ThreeJS) by pressing the escape key on the keyboard? I have a different function in mind for this key in my project! Appreciate any assistance in advance ...

Approach to converting between metric and imperial measurements for weight and height

When prompting users to enter their weight, it's important to consider both metric and imperial units. One convenient approach might be to provide a dropdown menu for users to choose their preferred unit of measurement before filling in the correspond ...

Retrieving binary content from an HTML5 Canvas using base64 encoding (readAsBinaryString)

Is it possible to extract binary data from an HTML Canvas? Currently, I have the following HTML code displaying an input file and a canvas below it: <p><button id="myButton" type="button">Get Image Content</button></p> <p>In ...