How can the onclick attribute be modified in an HTML document?

I am looking to update the data-pro-bar-percent attribute of a progress bar from 80 to 100 when a specific link is clicked.

The change in attribute needs to be as follows: data-pro-bar-percent="80" --> data-pro-bar-percent="100"

This is the current HTML code snippet:

<a class="button" href="#">Click Link</a>
<div class="pro-bar-container color-green-sea">
    <div class="pro-bar bar-100 color-turquoise" data-pro-bar-percent="30" data-pro-bar-delay="4000">
        <div class="pro-bar-candy candy-ltr"></div>
    </div>
</div>

Answer №1

Links should not be treated as buttons! Always use buttons for better accessibility and user experience.

To change a data attribute, you can utilize the DOM's setAttribute method. It's important to select the right element - if there are elements with the same class name, consider using

this.children.children.setAttribute()
to pinpoint the specific nested child you want to modify.

You can easily add an event listener to a link or button element (remember, buttons act as submit buttons in forms by default). Make sure to assign a function that will update the data attribute values upon interaction.

<button id="myButton">Click Me</button>

var button = document.getElementById("myButton");
button.addEventListener("click",function() {
    document.getElementsByClassName("pro-bar")[0].setAttribute("data-pro-bar-percent","100");
}, false);

It's worth noting, as highlighted by @rlemon, that getElementsByClassName has limited browser support compared to querySelector. It's advisable to use the latter method for more reliable results.

document.querySelector(".pro-bar").setAttribute("data-pro-bar-percent","100");

Answer №2

I recommend utilizing the .data() method over the .attr() method for accessing and updating current data values. It offers better efficiency and performance.

Learn more about using .data() in jQuery here

$('.btn').on('click', function(){
    var currentVal = $('.progress-bar').data("progress-bar-value");
    $('.progress-bar').data("progress-bar-value", currentVal += 10);
});

Answer №3

To implement jQuery, start by assigning an id to your link:

<a class="button" id="myLinkBtn" href="#">Click Here</a>

Next, if you wish to set the value of data-pro-bar-percent to 100 immediately, use the following code:

$("#myLinkBtn").on("click", function(){ 
    $(".pro-bar .bar-100 .color-turquoise").attr("data-pro-bar-percent","100");
});

Alternatively, if you prefer to increase the current bar value by 20, you can utilize this snippet:

$("#myLinkBtn").on("click", function(){
    var targetElement = $(".pro-bar .bar-100 .color-turquoise");
    var currentPercent = parseInt(targetElement.attr("data-pro-bar-percent")) + 20;

    targetElement.attr("data-pro-bar-percent", currentPercent);
});

Feel free to reach out if you have any further questions or concerns!

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

Operating PHP program from html on Beaglebone Black Rev C Debian

I've created a JavaScript program that utilizes node.js to manage GPIO from an IO.html page to the beaglebone. I simply initiate the JavaScript with "node myscript.js". Now, I'm looking to incorporate a PHP file that will store data from the IO. ...

What could be the reason for the absence of Mock Service Worker in a React project that has Typescript enabled?

After attempting to integrate Mock Service Worker into my React project with Typescript support, I encountered errors when running the npm install msw --save-dev command. The terminal displayed the following messages: PS F:\Programming\React Prac ...

Is it true that URL parameters can be found in two distinct locations within this.props in react-router?

<Route path="lookbook" component={Photos} onEnter={onPageEnter}> <Route path=":photoIdentifier" component={PhotoDetailsModal} onEnter={onPageEnter}> </Route> </Route> While in the PhotoDetailsModal, I used console.log to check ...

Measuring Page Loading Status using Ajax

I'm still learning Ajax and JQuery, and I've been having a tough time putting this together. My goal is to use ajax navigation to load URLs and implement back and front navigations with popstate. The code below is functional, but I'm facing ...

In Javascript, you can enhance your axes on a graph by adding labels at both the

Is there a way to add labels at the beginning and end of the axes to indicate the importance level, such as "not very important" and "very important"? I am currently utilizing a slider program from here. Since I am new to JavaScript, I would greatly appre ...

When the page is closed or the back button is pressed on an iframe, a color box

Looking for assistance with my code. I am currently utilizing colorbox to display an <iframe> form after a user submits their zip code. There is an additional action I want to trigger only when the user tries to close the iframe or navigate back in t ...

Yeoman - A guide for integrating an express server task into Gruntfile.js from the generator-angular template

Currently, I am diving into the world of Grunt and attempting to integrate an Express server into my AngularJS application that was initially created with Yoeman. I've made adjustments to the following task as shown below: grunt.registerTask('s ...

What is the best way to choose elements based on a specific data- attribute?

Is it possible to utilize contains: within a selector in order to target all elements with a data- attribute, or is there an alternative method for selecting all such elements? For instance, targeting all elements containing "NL" or "UK". ...

Assign a JavaScript variable upon clicking a polygon on Mapbox

I have a MapBox map that consists of approximately 800 polygons representing census tracts, created using TileMill. The map has been integrated into an HTML page alongside a D3.js chart. A drop-down menu on the page allows users to select one of the 800 ce ...

The initialization process of Vue.js router is compatible with router.map, but not with the Router constructor

I'm experiencing an issue in my app where routes work fine when I use router.map({}) with the vue-router, but they fail to work when I pass them directly in the constructor. Any insight into why this might be happening? // Routes that work: const rou ...

Enhanced Rating System for Asp.Net

How can I retrieve the selected value (CurrentValue) of the ASP.NET Rating control in javascript? I have it implemented within a datagrid, and I am facing difficulty in accessing the CurrentValue property. Any suggestions or solutions for this issue woul ...

SPFx WebPart - Tabbed Interface

I am new to developing SPFX WebParts and currently working on creating a Tab WebPart. The HTML appears to be rendering correctly, but I'm facing issues with the Javascript functionality not firing as expected. Any assistance or guidance on how to prop ...

The HTML view is unable to display the CSS style due to a MIME-type error

I have recently developed a very simple Express app that is supposed to display a single view called home.html from the view directory. Although the home.html file is being shown, none of the CSS styles I added seem to be loading. The console is throwing t ...

Is there a way to display only the specific child div within the parent div using JavaScript without affecting the others?

   **** Sorry for the lengthy title **** Today I encountered a problem that I would like to discuss with all of you. When I click on a "COMMENT" button, instead of triggering JavaScript code to display a CHILD.div inside the corresponding ...

Attempting to transfer information from a JSON file to a Netflix-inspired platform

Images I am currently working on integrating data from my json file export const products = [ { name: 'iPhone 11', image: '/assets/images (7).jpeg', time: '1 hour 14mins', age: '+16&apo ...

The middleware function in my express server is not being identified

Currently, I am tackling server-side rendering in React and have developed a basic server in Express. However, I'm encountering the "TypeError('app.use() requires a middleware function')" error repeatedly. Below is a snippet of my app.js: v ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

What steps should I take when dealing with two dynamic variables in a mediator script within the WSO2 ESB?

I'm facing an issue with my if condition - it doesn't work properly when the value is static. However, when I make `annee2` and `annee1` static (for example =2019), it works fine. Here's the code snippet: <script language="js"&g ...

Run code from an inline script that is retrieved from an external origin

I am encountering an issue with my React app where I need to fetch index.html from one server location and run its scripts from another server location: const entries = await axios.get(`http://localhost:xxx`); let domParser = new DOMParser(); let tempDO ...

Can a website built on Express.js be optimized for SEO?

Would pages created with the traditional route structure provided by Express (e.g. ) appear on Google's Search Engine Results Page as they would for a Wordpress blog or PHP website using a similar path structure? ...