user1438026
user1438026

Reputation: 999

Recording a link click then saving to local storage

Is this the correct code for recording a link click then saving to local storage and then displaying the image with link in a div?


<script>
    var links = [ 'one': 1, 'two': 2, 'three': 3 ];
    function saveLink(that){
        links[links.length] = that.element.src;
        document.getElementById('linkList').innerHTML += that.element.src+"<br>";

        localStorage.setItem('links', JSON.stringify(testObject));
    }
    </script>

    <img src="http://domain.com/image.png" onclick="saveLink(this);" />



    <div id='linkList'>
    <script>
        var retrievedObject = localStorage.getItem('links');

    console.log('retrievedObject: ', JSON.parse(retrievedObject));

    </script></div>

Upvotes: 0

Views: 1728

Answers (1)

DGS
DGS

Reputation: 6025

No it is not the correct way to "display the image with link in a div" console.log will log to the console as its name suggests not create elements in the DOM. Since you have the question tagged as jQuery i am going to assume you are using it with my answer.

//Assuming you want the click handler to be attached to all images on the page
$('img').click(function(){
    $('#linkList').append('<a href="' + $(this).attr('src') +'">Image</a>')   
});

This will append a new <a> tag which is a link to the image that you clicked on.

That will give you new code which is as follows

<script>
    $(document).ready(function () {
        //Assuming you want the click handler to be attached to all images on the page
        $('img').click(function () {
            $('#linkList').append('<a href="' + $(this).attr('src') + '">Image</a>')
        });
    });
</script>
<img src="http://domain.com/image.png" />
<div id='linkList'>
</div>

Upvotes: 1

Related Questions