Monday, August 27, 2012

html – Making a JavaScript code works with any element


document.getElementById(\"but\").onclick = showDropDown;

function showDropDown(e) {
document.getElementById(\"but\").onclick = function() {};
if (e.stopPropagation) e.stopPropagation(); // W3C model
else e.cancelBubble = true; // IE model
document.getElementById(\"window\").style.display = \"inline-block\";
document.onclick = function(e) {
var ele = document.elementFromPoint(e.clientX, e.clientY);
if (ele == document.getElementById(\"but\")) {
hideDropDown();
return;
}
do {
if (ele == document.getElementById(\"window\")) return;
} while (ele = ele.parentNode);
hideDropDown();
};
}

function hideDropDown() {
document.onclick = function() {};
document.getElementById(\"window\").style.display = \"none\";
document.getElementById(\"but\").onclick = showDropDown;
}​


<input id=\"but\" type=\"button\" value=\"pressMe\" />
<div id=\"window\" style=\"display:none\">popup</div>


Demo: http://jsfiddle.net/nazym/


I was trying to make the JavaScript code dynamic using variables instead of the specified elements\’ names but I could not. It always returns errors. I want to link it with different elements.


update

I want to replace the ids of the elements in the JavaScript code with variables so I can use it with any element.I tried to do it but failed. Basically, I want to use variables instead of the ids of the element and link it to the elements somehow again.






Rating: 3 out of 5 based on 3 ratings



The post html – Making a JavaScript code works with any element appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/html-making-a-javascript-code-works-with-any-element.html

No comments:

Post a Comment