0

I want to create a html5 game. The game master uses a chat-like system to communicate with the user. The chat messages should appear one after another, each with a specific delay. I named the elements using the id parameter from 1 to n and I'm just looping through the ids to display them one after another.

I want to set a custom delay for every message, without writing anything inside of the .js file I'm using. The best way would be writing it inside of the html tag, like this: <p class="msg" id="1" delay="0">. How can I access the value stored in delay, when I'm accessing the element with $("#1")?

3 Answers 3

3

Use a data-* attribute instead and use jquery data api, other wise you can just do $('#1').attr('delay') but using a data-* would be more correct.

<p class="msg" id="1" data-delay="0">

and

$('#1').data('delay'); //This will return 0 as a number rather than as a string which would if you access it with attr

You can see a major difference here Demo

Sign up to request clarification or add additional context in comments.

2 Comments

+1 I had the doubt why all are preferring data-* attributes. But with your demo it is very clear and understood. But this can be rectified by parsing (parseInt($('#2').attr('delay'),10))right?
@PraveenJeganathan Yes Praveen. Using the data attribute you get that flexibility (apart from rectifying the issue of adding an invalid attribute delay to html), You don't need to access DOM (avoiding a DOM operation while doing attr) instead just access if from internal cache using data api (or dataSet.delay incase of vanilla JS ) and it can cast anything i.e object, array, numeric values etc without having to parse it separately.
1

You can make use of data elements. This would mean that in your HTML tags you add data-custom = 'value', and then you can access it with $("selector").data("custom").

In this case it would mean that you'd have: <p class="msg" id="1" data-delay="0"> and use it with $("p.msg").data("delay").

Comments

1

First of all, you want to use data-attributes. Rather than delay, use data-delay, like this:

<p data-delay="0">Text</p>

You can access this in jQuery in two ways, either by using $('p').data('delay') or $('p').attr('data-delay').

Secondly, you probably don't want to use numbers as your ID. CSS can't reference IDs by values that start with numbers. If you must have an attribute that is a number, I recommend using data-id instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.