I'm new to javascript and I need some help. I created a function that adds a div with the id "test_div" to the body. However, when I try to set the position using "element.style.position", it doesn't work. I figured out that I can apply styles using "element.style.cssText" instead. I even tried using a variable with "document.getElementById()" after creating the element, but that didn't work either. I'm not sure what I'm doing wrong. Any assistance would be greatly appreciated. Thank you for your help. Please excuse any mistakes in my English.
Here is the HTML file:
<!DOCTYPE html>
<html lang="en>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="test.js">
</script>
</head>
<body>
<button onclick="add('Clicked ', 0)">Click</button>
</body>
</html>
And here is the JavaScript file:
var element_id = "test_div";
var default_timeout = 3;
var element_bg_color = "rgba(0, 0, 0, .5)";
var element_font_color = "#fff";
var element_pointer_events = "none";
var element_position = "fixed";
var element_top = "0";
var element_left = "0";
var element_padding = '.3em .6em';
var element_margin = "0";
var element_border_radius = "0 0 5px 0";
var add = function(string, timeout){
if(typeof(timeout) === 'undefined'){
timeout = default_timeout;
}
var element = document.createElement('div');
element.id = element_id;
element.style.position = "fixed";
element.style.cssText = "top: 0; left: 0; background-color: " + element_bg_color + "; margin: 0; padding: .3em .6em; border-radius: 0 0 5px 0; color: " + element_font_color + "; pointer-events: " + element_pointer_events + ";";
element.innerHTML = string;
if(document.getElementById(element_id) === null){
document.body.appendChild(element);
}else{
document.body.removeChild(element);
document.body.appendChild(element);
}
if(timeout > 0){
timeout *= 1000;
setTimeout(function() {
document.body.removeChild(element);
}, timeout);
}
};