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

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Execute Cheerio selector once the page has finished loading

Hey there! I'm trying to extract the URL value of an iframe on this website: I've checked the view page source but couldn't find the iframe. Looks like it's loaded after the page is fully loaded through JavaScript. Could it be that ...

Unable to find the import "@mui/x-charts/PieChart" in the file "src/components/Pie/Pie.jsx". Could the file be missing or spelled incorrectly?

I utilized the PieChart component in my pie.jsx file pie.jsx import { PieChart } from '@mui/x-charts/PieChart'; const Pie = () => { return ( <div> <PieChart series={[ { data: [ ...

What is the best way to access query string parameters within NextJS middleware?

In the context of NextJS middleware, I have successfully obtained the nextUrl object from the request, which includes details like the pathname. However, I am now wondering how to extract query string parameters directly within the middleware. Although I c ...

Guide on deactivating the HTML drawer layout on a website with Selenium using Java

I am currently working on automating a website and I have encountered a challenge with a drawer Menu Panel. My goal is to open the menu, verify certain elements within it, and then close or hide it. However, I am facing difficulty in closing/hiding this d ...

Linux web server blocking requests across different domains, even with correct Access-Control-Allow-Origin headers set

I am facing an issue with my Ubuntu web server running a React app. There are two files on the server that handle requests made by the website, but for some reason, clients are unable to make requests to the server. Server.js: const express = require(&apos ...

Is there a way to update an image from the camera in the background without having to refresh the entire

Utilizing a PHP script (currentimage.php) to obtain a snapshot from my CCTV IP camera has been successful: <?php while (@ob_end_clean()); header('Content-type: image/jpeg'); // create curl resource $ch = curl_init(); curl_setopt($ch, ...

jQuery insert custom text into HTML and eliminate malfunctioning elements

Using jQuery, I have created a form where the entered text is appended to certain elements. This functionality works correctly. Additionally, I have included a remove link with each added element. When someone clicks on the remove button, it should remove ...

Performing an AJAX request within another AJAX request using jQuery

$.ajax({ type: 'POST', url: searchpage, dataType: "json", data: { id: id }, success: function(data) { var id1 = []; for(var i = 0; i < data.length; i++){ id1 .push({ ...

What could be causing NestJS/TypeORM to remove the attribute passed in during save operation?

Embarking on my Nest JS journey, I set up my first project to familiarize myself with it. Despite successfully working with the Organization entity, I encountered a roadblock when trying to create a User - organizationId IS NULL and cannot be saved. Here ...

Extract the content from the division and set it as the image source

Looking for a way to retrieve the content from a div and insert that into the 'src' parameter of an image. Working on a project where JSON is used to load translation files, preventing me from loading images directly, but I want to at least load ...

Creating a button that allows updates without refreshing the page can be achieved by implementing

Here are the items I have: <table> <tr> <th> id </th> <th> name </th> <th> update </th> </tr> <tr> ...

Error encountered: Vue.js encountered an unexpected token, which is 'export'

Having an issue with Google location autocomplete, specifically this error: SyntaxError Unexpected token 'export' Here is the link to the functional code: https://codesandbox.io/s/nifty-bardeen-5eock ...

Stagnant variable value after onClick event

After exploring various solutions, none seem to quite fit my needs. I want to update the variable "currentIndex" when a user clicks on an image. Currently, the change occurs within the onClick function but does not affect the outside variable. I am unsur ...

Add video details to the database using the API

I currently have my own database of YouTube videos which includes the video IDs found in the video links. My goal is to find a way to insert both the title and description of these videos into the database using the YouTube API and MySQL. Although I have ...

How can I use jQuery to set a JSON array as the value of a specific index in a jQuery array?

Imagine that I am fetching JSON data from two different PHP files, first.php and second.php, using jQuery. I want to store this data in an array named var total = [index1,index2]. The JSON data from the first.php should be assigned to the first index of th ...

Steps for attaching an onclick event to a dynamically created div

I'm trying to figure out how to set up an onclick event for dynamically generated div elements in my HTML file. Each of these divs has a unique id. How can I use the id to add the onclick behavior? This is the code I have for generating the divs: fu ...

Guide for creating a CORS proxy server that can handle HTTPS requests with HTTP basic authentication

For my http requests, I've been utilizing a CORS-Proxy which works well for me. However, I recently stumbled upon an API for sending emails which requires http basic authentication for https requests. I'm uncertain of how to go about implementing ...

The accordion won't function properly if it is added using append() after the document is ready

I have implemented a button to add an accordion, but unfortunately it doesn't seem to be working properly. I am unsure of how to troubleshoot and resolve this issue. If the accordion HTML is appended after the document.ready() function, then the accor ...

Review the Drawer Item's Render Method

I have been using react-native with expo and following a specific guide closely: Is there an alternative way to implement this without the use of icons at the moment? Upon compiling, I encountered an error regarding the Render Method of DrawerItem. I&apo ...