Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to get and change element Title

I want to change images inside a div when a link is clicked. I did that, but I can't retrieve the TITLE of the image from the TITLE of the link.

JavaScript

function changeImage(element) {
    document.getElementById('imageReplace').src = element;
}

HTML 1

<a href="#" title="PIC1" onclick="changeImage('pics/1.jpg');return false;">my link</a>

HTML 2

<img src="pics/empty.png" id="imageReplace"/>

When I click the link shown in HTML1, the image changes where the HTML2 code is, but the "title" attribute is not retrieved and nothing pops up when the mouse is over the new pic. I want to retrieve this title attribute.

Can anyone help?

like image 549
Alex Avatar asked Oct 26 '25 20:10

Alex


2 Answers

Modify your function a little:

function changeImage(src, a) {
    var img = document.getElementById('imageReplace');
    img.src = src;
    img.title = a.title;
}

and HTML:

<a href="#" title="PIC1" onclick="changeImage('pics/1.jpg', this);return false;">my link</a>

So you basically pass HTMLAnchorElement object (a tag) into changeImage function where you can use its properties like title. There you set image title equal to link one.

like image 51
dfsq Avatar answered Oct 28 '25 09:10

dfsq


Link:

<a href="#" title="PIC1" onclick="changeImage.call(this,'pics/1.jpg');">my link</a>

Image:

<img src="pics/empty.png" id="imageReplace"/>

Function:

var changeImage = function(element) {
    document.getElementById('imageReplace').src = element;
    document.getElementById('imageReplace').title = this.title;
    return false;
}

Fucntion.prototype.call()

The call() method calls a function with a given this value and arguments provided individually.

like image 31
Frogmouth Avatar answered Oct 28 '25 09:10

Frogmouth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!