miki24p
miki24p

Reputation: 31

Add a link to an image in a Javascrip

hello everybody!

First of all I have to tell you I'm a newbie in terms of HTML, Javascript and coding in general. But I spent last weeks to learn as much as I can. Now, I run a website and my dev team is not workgin with me anymore, then I have to do all by myself.

My problem is: I have a sort of "big banner" and the image shown is automatically picked up based on your browser resolution (that's fine, I asked for this). Now, what I'm trying to do is to add a hyperlink to this image. I tried many thing, but I couldnt.

Please could you tell me how to edit this code?

Thank you

Miki

<div class="main top">
    <div class="main-holder">
        <div class="cover-holder big-img-holder" id="img-holder">
            <script>
                function randomInteger(min, max) {
                    var rand = min + Math.random() * (max - min)
                    rand = Math.round(rand);
                    return rand;
                }
                var rand = randomInteger(1, {{$lang.extras.number_screenshots_rotations}});

                var picture = document.createElement('picture');
                                    var source = document.createElement('source');
                source.srcset = '{{$config.statics_url}}/images/bg_rotations/extras-' + rand + 'bd_HD.jpg';
                source.setAttribute('media', '(max-width: 2000px)');
                var img = document.createElement('img');
                img.src = '{{$config.statics_url}}/images/bg_rotations/extras-' + rand + 'bd.jpg';

                picture.appendChild(source);
                picture.appendChild(img);
                document.getElementById('img-holder').appendChild(picture);
            </script>
        </div>

Upvotes: 3

Views: 64

Answers (2)

Mrob
Mrob

Reputation: 341

Usually you can set a hyper link with the HTML tag <a>

So you could try

    <a href="your-URL">
        <div class="cover-holder big-img-holder" id="img-holder">
            <script>
               ...
            </script>
        </div>
    </a>

Upvotes: 2

Nicol&#225;s Videla
Nicol&#225;s Videla

Reputation: 44

Wrap the script in something like

<a id="img-link">

or just change img-holder to be an <a> instead of a <div>

Then somewhere in your script set the url for that <a> container

document.getElementById("img-link").href="url";

There's no href attribute to an image itself, so you must provide it to <a>

That is if you wanna do it dynamically, if the url is always the same, just wrap your <script> block with this

<a href="#">
 <img>
</a>

It is easier when you know that DOM is gonna have the same structure, in this case, an image, and an <a> tag wrapping it, just set ids for both, and manipulate their attributes, otherwise, you can also create this <a> element in Javascript, and set the image with .setChild() to it

Upvotes: 0

Related Questions