Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting title attribute with Javascript function

I am trying to find, if I can pass a value on the title attribute of a label element using Javascript?

I have tried the following Javascript code:

function myFunction()
{
    return "Hello!";
}

And a piece of HTML code:

<label title="myFunction()">TEST</label>

But, this isn't working. It just show the 'myFunction()' as a text.

Is it possible, what I am trying to do? If yes, what is the correct syntax?

like image 670
Redg Avatar asked Oct 09 '12 20:10

Redg


People also ask

What is a title attribute in JavaScript?

The title attribute specifies extra information about an element. It can be shown as a tooltip text when the mouse moves over the element.

How do you display a title in JavaScript?

Put in the URL bar and then click enter: javascript:alert(document. title); You can select and copy the text from the alert depending on the website and the web browser you are using.

What is the function of title attribute?

The title attribute specifies extra information about an element. The information is most often shown as a tooltip text when the mouse moves over the element.

How do you title an attribute?

The title attribute is used to specify extra information about the element. When the mouse moves over the element then it shows the information. Supported Tags: It supports all HTML elements. Attribute Value: This attribute contains single value text which is used as the tooltip text for an element.


2 Answers

<label id='mylabel'>TEST</label>
<script>
    function myFunction() {
        return "Hello!";
    }

    document.getElementById('mylabel').setAttribute('title', myFunction());
</script>

Should do the job. It first selects the label and then sets the attribute.

like image 162
daknøk Avatar answered Sep 23 '22 13:09

daknøk


You can't inline javascript like this.

What you may do is

1) give an id to your label and put this at the end of your body

<script>
   document.getElementById('myId').title = myFunction();
</script>

Demonstration

2) if you really want to inline the call, write this at the point where you want your label :

<script>
     document.write('<label title="'+myFunction()+'">TEST</label>');
</script>

(this is really not recommended)

like image 26
Denys Séguret Avatar answered Sep 22 '22 13:09

Denys Séguret