5 Website Development Tips To Boost Your Business Growth Exponentially

In HTML5, as well having a range of new elements and attributes to choose from, you can use your own custom data attributes. These can be potentially useful in lots of situations, but should only be used in cases where there is not an existing attribute designed to suit the purpose you are using the custom attribute for. In this tutorial we will run through a basic example of using custom data attributes in HTML5, with JavaScript code retrieving the attributes to create an interactive website component.

HTML5 and JavaScript: Custom Data Attributes

Custom data attributes are even easier to use if you are using jQuery, but in this tutorial we will focus on the basic JavaScript involved so that you have a clear idea of the syntax. We are going to create a simple Web page in which the user can choose from a list of songs. This could be used as part of a Web application in which the user makes up a playlist. The user will be instructed to select songs up to a maximum duration of ten minutes. The duration of each song in the list will be included in the input element markup using custom data attributes. As the user selects songs using the checkbox controls, the total duration will update to reflect the total length, highlighting in red if the duration exceeds the specified time limit. This trivial example would of course need a lot of enhancement to form a truly useful component, but should demonstrate the essentials of custom attributes in HTML5.

Page Content

Create a new HTML5 page using the following outline unless you are working with an existing page:

 <!DOCTYPE HTML> <html> <head> <script type="text/javascript">  </script> </head> <body>  </body> </html> 

Add an informative introductory paragraph to the body section of the page:

 <p>Choose songs - <strong>maximum 10 minutes</strong>.</p> 

Next in the body, add a section in which we will display the running total as the user selects (and deselects) songs:

 <p>Total length: <span id="minutes">0</span> mins <span id="seconds">0</span> seconds.</p> 

Notice that this section contains two span elements each with a unique ID attribute. We will use these to set the number of minutes and seconds each time the user interacts with the song choice controls. We initialize the two sections to zero and will add or subtract when the user checks or unchecks the boxes for each song. Next add a form element:

 <form> </form> 

Inside the form, we are going to add checkbox input elements with the following initial structure:

 Song 1: <input type="checkbox" name="song1"/><br/> 

Each checkbox will be preceded by a text label, which you can of course change if you like. The checkboxes will also have a name attribute, which you will need for further processing although we will not use it for this tutorial. We will be adding the following custom data attribute to each checkbox input:

 data-duration="126" 

Custom data attributes in HTML5 elements should always begin with “data-” as in this example. In this case the attribute is going to represent the song duration, so is an integer indicating a number of seconds. The checkboxes are also going to include a click event listener specifying a JavaScript function to execute when the user either checks or unchecks the input:

 onclick="updateDuration(this)" 

We pass the element itself for manipulation in the function. Add a few of these elements to the form in your page:

 Song 1: <input type="checkbox" data-duration="126" name="song1" onclick="updateDuration(this)"/><br/> Song 2: <input type="checkbox" data-duration="200" name="song2" onclick="updateDuration(this)"/><br/> Song 3: <input type="checkbox" data-duration="185" name="song3" onclick="updateDuration(this)"/><br/> Song 4: <input type="checkbox" data-duration="129" name="song4" onclick="updateDuration(this)"/><br/> Song 5: <input type="checkbox" data-duration="122" name="song5" onclick="updateDuration(this)"/> 

Retrieve Durations

Let’s now add the function we specified as click listener for the checkboxes and retrieve the duration value from the clicked checkbox. In the script section in your page head:

 function updateDuration(elem){ //update page } 

Inside the function, first retrieve a reference to the two elements representing the total minutes and seconds:

 var minElem=document.getElementById("minutes"); var secElem=document.getElementById("seconds"); 

Now retrieve the current minutes and seconds displayed in these, which will change each time the user interacts with the controls:

 var currMins=parseInt(minElem.innerHTML); var currSecs=parseInt(secElem.innerHTML); 

The elements will return their content as strings, so we parse them as integers so that we can add or subtract with them. Next let’s get the duration from the custom data attribute in the checkbox the user has clicked. We can do this in one of two ways. First, try retrieving it using the getAttribute method:

 var newLen=parseInt(elem.getAttribute("data-duration")); 

Alternatively, you can use the dataset for the element:

 var newLen=parseInt(elem.dataset.duration); 

Choose whichever method you prefer – they should have the same result. Notice that the dataset version does not need to include the “data-” prefix, just the part of the custom data attribute name that appears after that. Now let’s translate the retrieved duration attribute value to minutes and seconds for display:

 var mins=Math.floor(newLen/60); var secs=newLen%60;  

Update Display

Now we can update the total duration display using the values retrieved from the custom attributes. There will be two possible responses to the user clicking a checkbox. If the checkbox has been checked, we will add the new duration to the total. If the checkbox has been unchecked, we will subtract the song duration from the total. Still inside the function, initialize a variable to keep track of the new total:

 var newTotal=0; 

Now add a conditional to test whether the input element is checked or not:

 if(elem.checked){ //box has been checked } else{ //box has been unchecked } 

Inside the if block, update the text displayed in the minute and second spans by adding the duration from the clicked input element:

 minElem.innerHTML=currMins+mins; secElem.innerHTML=currSecs+secs; 

Still inside the if, update the total variable, converting to seconds, adding the existing minutes, seconds and new seconds:

 newTotal=(currMins*60)+currSecs+newLen; 

In the else block, carry out the same process but this time subtracting to reflect the fact that the box was unchecked:

 minElem.innerHTML=currMins-mins; secElem.innerHTML=currSecs-secs; newTotal=(currMins*60)+currSecs-newLen; 

After the if and else blocks but still inside the function, let’s now check whether the new total has exceeded the maximum ten minute duration, making the elements display in red if it has, black if it hasn’t:

 if(newTotal>600) {minElem.style.color="#ff0000"; secElem.style.color="#ff0000";} else {minElem.style.color="#000000"; secElem.style.color="#000000";} 

Save your page and open it. When you click the boxes, the total should update.

page updating

If the total exceeds ten minutes, the numbers should display in red:

length exceeded

Experiment with the page, checking and unchecking to see the display update.

Conclusion

In this tutorial we have worked through the essentials of including and retrieving custom data attributes with HTML5 and JavaScript processing. Below is the complete source code for the tutorial, so you can check yours if you are unsure about anything:

 <!DOCTYPE HTML> <html> <head> <script type="text/javascript"> function updateDuration(elem){ var minElem=document.getElementById("minutes"); var secElem=document.getElementById("seconds"); var currMins=parseInt(minElem.innerHTML); var currSecs=parseInt(secElem.innerHTML); var newLen=parseInt(elem.dataset.duration);//parseInt(elem.getAttribute("data-duration")); var mins=Math.floor(newLen/60); var secs=newLen%60;  var newTotal=0; if(elem.checked){ 	minElem.innerHTML=currMins+mins; 	secElem.innerHTML=currSecs+secs; 	newTotal=(currMins*60)+currSecs+newLen; } else{ 	minElem.innerHTML=currMins-mins; 	secElem.innerHTML=currSecs-secs; 	newTotal=(currMins*60)+currSecs-newLen; }  if(newTotal>600) {minElem.style.color="#ff0000"; secElem.style.color="#ff0000";} else {minElem.style.color="#000000"; secElem.style.color="#000000";} } </script> </head> <body> <p>Choose songs - <strong>maximum 10 minutes</strong>.</p> <p>Total length: <span id="minutes">0</span> mins <span id="seconds">0</span> seconds.</p> <form> Song 1: <input type="checkbox" data-duration="126" name="song1" onclick="updateDuration(this)"/><br/> Song 2: <input type="checkbox" data-duration="200" name="song2" onclick="updateDuration(this)"/><br/> Song 3: <input type="checkbox" data-duration="185" name="song3" onclick="updateDuration(this)"/><br/> Song 4: <input type="checkbox" data-duration="129" name="song4" onclick="updateDuration(this)"/><br/> Song 5: <input type="checkbox" data-duration="122" name="song5" onclick="updateDuration(this)"/> </form> </body> </html> 

Read more http://www.webdesign.org/html5-and-javascript-custom-data-attributes.22312.html


Published on: Mar 03, 2021

Categories: Web Development

    No Comments yet! Be the first one to write.


    Leave a Reply

    Your email address will not be published. Required fields are marked *

    user IP : 3.145.108.9 | Server_IP: 192.168.111.161 | IP_Score: