Reputation: 169
I am trying to load a button on the page using jQuery and when someone clicks that button I want the onclick
function to happen and id value to be saved in local storage.
However this gives me a null when logged into a console! Is this wrong? And how can I achieve this?
var str = '<div class="row">
<div class="col-md-4">
<div class="thumbnail">
<img src="' + poster + '"alt="Poster_here">
<div class="caption"><h3>' + title +'</h3><p>' + desc + '</p><p>
<a href="" class="btn btn-primary" role="button"
script="onclick()=function(){localStorage.setItem("idd","' +
id + '");' +'}">Read More and Explore</a> </p></div></div></div>
</div>';
$('#add_all_here').append(str);
HTML:-
<div class="container-fluid">
<div id="add_all_here">
</div>
</div>
Upvotes: 1
Views: 75
Reputation: 31024
Your code run as expected.
I think i know what causing you to think it's not running.
This line inside the <a>
tag: script="onclick()=function(){localStorage.setItem("idd","' + id + '")
This is not a way to attach event handlers.
You need to pass a function reference to the attribute with the event's name.
So instead of script=onclick...
It should be: onclick='functionName(event)'
Another thing, is that you need to prevent the redirection to the website to provide time to set things in local storage and only then redirect the client.
So you can use the event.preventDefault()
to stop the redirection, and then grab the url from href
attribute and set the window.location
.
Here is a working example with your modified code (i can't use local storage in snippets so i used console.log
):
function setLocalStorage(e){
e.preventDefault();
var id = e.target.getAttribute('data-id');
var url = e.target.href;
console.log('saving id - ' + id);
console.log('redirecting to - ' + url);
//window.location = url; //this will redirect
}
var poster = 'sdsd',
title = 'blah',
desc= 'skjdksdj ksjd ',
id= 457
var str = '<div class="row"><div class="col-md-4"> <div class="thumbnail"> <img src="' + poster + '"alt="Poster_here"><div class="caption"><h3>' + title +'</h3><p>' + desc + '</p><p><a href="http://example.com" class="btn btn-primary" data-id="' + id + '" role="button" onclick="setLocalStorage(event)">Read More and Explore</a> </p></div></div></div></div>';
$('#add_all_here').append(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<div id="add_all_here">
</div>
</div>
Upvotes: 1