2

I want to make an image which, when clicked, displays some additional information about the image, such as the title. Below is some code I have tried, which seems to work. However, this was just after deciding on my own to try adding a custom attribute "title", rather than reading somewhere that this was the way to do this. So, even though this works for me, I would like to know whether this is good practice, or whether there is a recommended way to do this?

HTML:

<img id="test_image" src="images/image1.jpg" title="Test Image">

jQuery:

$("#test_image").click(function()
{
    alert(this.title);
});
1
  • If you want to read a custom attribute, you would have to do something similar like alert($(this).attr("custom")); However, I would recommend against this Commented Dec 22, 2016 at 1:55

1 Answer 1

3

title isn't a custom attribute, it's a standard attribute. It gets displayed in a tooltip when you hover over the element.

You should not create custom attributes. HTML5 has a standard mechanism for user-defined attributes, data attributes. All attributes beginning with data- are reserved for the programmer to use. And jQuery has a method for accessing these, .data().

$("#test_image").click(function()
{
    alert($(this).data('title'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="test_image" src="images/image1.jpg" data-title="Test Image">

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.