Changing an image after link click

I have the following code:

<table>
<tr>
<td>some text</td>
<td>
<a href="www.mydomain"  target=_blank><img src="my_image" /></a>
<td>
</tr>
</table>

When link is clicked
I need one of the two:

  1. The image “my_image” will change to second image,
    Or:
  2. a notification like “you have visited the link” will appear next to
    or next to some text.

Any ideas?

If you want this to happen without a page refresh you should be looking at javascript, not php.
Would you like the topic moved to the js forum?

yes, thanks

Hi @levy3108, to do that you first need a reliable identifier for that link so that you can get a reference with JS, say

<a href="www.mydomain" target=_blank id="my-domain-link"><img src="my_image" /></a>

Then you can add an event listener to dynamically change the image source:

// Get a reference to the link
var myDomainLink = document.getElementById('my-domain-link')
// ... and to the image child element
var image = myDomainLink.querySelector('img')
// Then listen to the click event
myDomainLink.addEventListener('click', function () {
  // When that event gets triggered, change the image source
  image.src = 'my_other_image'
}, { 
  // Unless we want to change the image again upon further 
  // clicks, we only need to listen to the event once
  once: true 
})

Thanks, Works :slight_smile:

The problem is - I’ve 10 links in one page. After clicking the first, clicking other links does not change the image.
Any ideas?

You’d need to replicate the above code for each of your links, though I would imagine there’s a way to do it without individually coding each one.

I think you could use a “data” attribute value something like

<a ..... data-alternate-image=“some.jpg”>
.....
image.src = a.dataset.alternate-image; 
1 Like

You’d need to give them a specific class then, say image-link. Then you have two options: either get all those links like

var links = document.querySelectorAll('.image-link')`

then iterate over them and bind an event listener to each as shown above. Or you bind a single event listener to a common parent element (in case of doubt, just document.body) and check if the event.target matches that class:

document.body.addEventListener('click', function (event) {
  var image
  
  if (event.target.matches('.image-link')) {
    image = event.target.querySelector('img')
    image.src = 'my_other_image'
  }
})

This pattern is called event delegation; an event dispatched from a given element bubbles up the DOM and sequentially triggers the same event on all of its ancestors, so you don’t have to add listeners to all the target elements themselves.

PS:

Ah yes, good point! (Would have to be camel-cased though…)

2 Likes

Thanks,
since I’m not that familiar with j.s. can you explain further?

If I have:

how’ll the java looks?

Thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.