How do I turn my image with a hover effect, into a clickable link

32 views Asked by At

So I don't know how to code but I'm using google sites to create a website and wanted to have an effect where an image changes from black and white to colour when you hover over it. I found the HTML code to do this but now I'm wondering if I can also make it so when you click the image, it will take you to another page.

Here is my HTML code with just the hover effect:

<div class="primary">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Across_the_lake_to_Vanbrugh_-_geograph.org.uk_-_4795570.jpg/640px-Across_the_lake_to_Vanbrugh_-_geograph.org.uk_-_4795570.jpg" />
</div>

<style type="text/css">
  .primary {
    cursor: pointer;
  }

  .primary img {
    filter: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='grayscale'><feColorMatrix type='matrix' values='0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0'/></filter></svg>#grayscale");
    /* Firefox 10+, Firefox on Android */
    -webkit-filter: grayscale(100%);
    filter: grayscale(100%);
    filter: gray;
    /* IE 6-9 */
    -moz-transition: all 0.2s ease-in;
    -o-transition: all 0.2s ease-in;
    -webkit-transition: all 0.2s ease-in;
    transition: all 0.2s ease-in;
  }

  .primary:hover img {
    filter: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='grayscale'><feColorMatrix type='matrix' values='1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0'/></filter></svg>#grayscale");
    -webkit-filter: none;
    filter: none;
  }
</style>
1

There are 1 answers

0
cssyphus On

Add this:

<script>
    const myTrigger = document.querySelector('div > img');
    myTrigger.addEventListener('click', () => {
        window.open('https://www.zerohedge.com/', '_blank').focus();
    });
</script>

The document.querySelector() lets you select the HTML element that you want to watch.

The addEventListener('click', function) allows you to specify that when someone clicks on that element, you want it to do something.

Finally, the anonymous arrow function tells the browser what to do when someone clicks on the trigger element.