Sibbo
Sibbo

Reputation: 3914

How to display delayed text in a simple way using js/jquery?

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")?

Upvotes: 0

Views: 813

Answers (3)

PSL
PSL

Reputation: 123739

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

Upvotes: 3

Jake
Jake

Reputation: 4234

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.

Upvotes: 1

skiwi
skiwi

Reputation: 69269

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").

Upvotes: 1

Related Questions