I am in the process of making a bookmarklet that pops up a div with various things in it… when you click on the link to open the bookmarklet twice, two bookmarklets pop up. how do I prevent this from happening?
index.html:
<html>
<head>
<title>Bookmarklet Home Page</title>
<link rel="shortcut icon" href="favicon.ico" />
</head>
<body>
<a href="javascript:(function(){code=document.createElement('SCRIPT');code.type='text/javascript';code.src='code.js';document.getElementsByTagName('head')[0].appendChild(code)})();">click here</a>
</body>
</html>
code.js:
function toggle_bookmarklet() {
bookmarklet = document.getElementById("bookmarklet");
if (bookmarklet.style.display == "none") {
bookmarklet.style.display = "";
}
else {
bookmarklet.style.display = "none";
}
}
div = document.createElement("div");
div.id = "bookmarklet";
div.style.margin = "auto";
div.style.position = "fixed";
content = "";
content += "<a href='javascript:void(0);'><div id='xbutton' onClick='javascript:toggle_bookmarklet();'>x</div></a>";
div.innerHTML = content;
document.body.appendChild(div);
Just check for the existence of
divbefore creating it.Also, since you already have a global reference to
div, you don’t need to search for it by id intoggle_bookmarklet. You can just referencediv. I’d try to choose a more unique name though, so as to avoid running in to naming collisions.Edit: For that matter, if you are going to use a global variable, you can simplify further. Don’t even bother giving it an id, just use the global reference: