javascript not rendering styles - javascript

I dont know why this code is not working!
html, css, javascript is not working in same html page
plz help I cant figure out this.. is it problem on browser or my code is wrong
every thing seems to be fine...
function render() {
var winW = window.innerWidth;
var winH = window.innerHeight;
alert('hello');
var overlay = document.getElementsByClassName('overlay');
var alert = document.getElementsByClassName('alertbox');
overlay.style.display = 'block';
overlay.style.background = 'blue';
overlay.style.height = winH + 'px';
overlay.style.width = winW + 'px';
overlay.style.border = '10px solid black';
}
.overlay{
display: none;
opacity: 0.8;
position: fixed;
background: #ccc;
z-index: 10;
width: 100%;
height:100%;
}
.alertbox{
display: none;
position: fixed;
background: magenta;
z-index: 10;
border-radius: 8px;
width: 500px;
}
<html>
<head>
<title></title>
</head>
<body>
<h3>Custom Alert Box Demo</h3>
<button type="button" onclick="alert('hello world')">render overlay</button>
<button type="button" onclick="render()">render overlay</button>
<div class="overlay"></div>
<div class="alertbox">
<div class="head"></div>
<div class="body"></div>
<div class="foot"></div>
</div>
</body>
</html>

See this fiddle
Your script has two errors. Please replace your script with the below given one
function render() {
var winW = window.innerWidth;
var winH = window.innerHeight;
var overlay = document.getElementsByClassName('overlay')[0];
var alert = document.getElementsByClassName('alertbox')[0];
overlay.style.display = 'block';
overlay.style.background = 'blue';
overlay.style.height = winH + 'px';
overlay.style.width = winW + 'px';
overlay.style.border = '10px solid black';
}
First error was in the line,
alert('hello');
because, you have a variable with name alert in your script and thus you will get an error alert is not a function in your console. If you want the alert to be shown, then you should rename your variable with name alert to some other name, may be for eg, rename it to alert1. Please see the fiddle.
Second error was in the line
var overlay = document.getElementsByClassName('overlay');
because document.getElementsByClassName() always returns an array.
According to the docs
getElementsByClassName() Returns an array-like object of all child elements which have all of
the given class names. When called on the document object, the
complete document is searched, including the root node. You may also
call getElementsByClassName() on any element; it will return only
elements which are descendants of the specified root element with the
given class names.
What I have done in the fiddle is that, I've selected the first element with the class name overlay using the index position 0. Similarly for the class alertbox.

Related

Unable to set div's background to linear gradient using Javascript

I'm trying to make a dynamic div element with styles including linear gradient. It should be displayed dynamically with a button, but the gradient does not get added.
var x = document.getElementById("btn");
x.addEventListener("click", addbox);
function addbox() {
var y = document.createElement("Div");
y.id = "div1";
y.style.border = "1px";
y.style.borderRadius = "20px";
y.style.height = "200px";
y.style.width = "500px";
y.style.backgroundImage = "linearGradient(to bottom right, yellow , cyan)";
document.getElementsByTagName("body")[0].appendChild(y);
}
#btn {
height: 50px;
width: 150px;
}
<button id="btn" onclick="addbox()"> CLICK ME TO DISPLAY </button>
Your code has a lot of little mistakes but here is something that works:
<!doctype html>
<html>
<head>
<title> ADD BOX ON CLICK FUNCTION </title>
<style>
#btn {
height: 50px;
width: 150px;
}
</style>
</head>
<body>
<script>
function addbox() {
var y = document.createElement("Div");
y.id = "div1";
y.style.border = "1px";
y.style.borderRadius = "20px";
y.style.height = "200px";
y.style.width = "500px";
y.style.background = "linear-gradient(to bottom right, yellow , cyan)";
document.getElementsByTagName("body")[0].appendChild(y);
}
window.addEventListener("DOMContentLoaded", (event) => {
var x = document.getElementById("btn");
x.addEventListener("click", addbox);
});
</script>
<button id="btn"> CLICK ME TO DISPLAY </button>
</body>
</html>
Your document.getElementById("btn") cannot work before the page has finished loading, so you have to put this inside a window.addEventListener("DOMContentLoaded") event that will fire only when your div is there
Remove the onclick="addbox()" from the div because it would fire twice per click
linearGradient spelling is wrong. It's linear-gradient
The property to apply the linear gradient is not y.style.backgroundImage but y.style.background

Why does this code use both `document.body` and `document.documentElement`?

Okay, so I'm trying to figure out how this JS code works.. Could you explain me some things?
There's the code (I've copied some of the w3schools' code, full: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_scroll_to_top
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
<script>
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>
I think that document.documentElement means it is a HTML and it contains all elements on the page. Am I wrong?
So why we need two variable setting in topFunction()? When I remove this line:
document.body.scrollTop = 0;
everything still working, so why we need this part of code? Thanks.
From the question title pre-edit:
What's the difference between document.body and document.documentElement?
document.body is the body element. document.documentElement is (in HTML documents) the html element.
So why we need two variable setting in topFunction()?
Because unfortunately, when scrolling the content of the main window, some browsers have historically scrolled html, and others body. You can try your current browser here:
var n, div;
for (n = 1; n <= 100; ++n) {
div = document.createElement('div');
div.innerHTML = String(n);
document.body.appendChild(div);
}
var bodyDisplay = document.getElementById("body-display");
var docElDisplay = document.getElementById("docel-display");
document.addEventListener("scroll", function() {
bodyDisplay.innerHTML = String(document.body.scrollTop);
docElDisplay.innerHTML = String(document.documentElement.scrollTop);
});
.top {
position: fixed;
height: 2em;
border-bottom: 1px solid #ddd;
background: white;
}
<div class="top">
<div>
body scrollTop:
<span id="body-display"></span>
</div>
<div>
documentElement scrollTop:
<span id="docel-display"></span>
</div>
</div>
<div>Scroll up and down</div>

How to copy a cloned node in an iframe to its parent with styles?

I'm trying to clone a <div> in an <iframe>, and append the cloned div to the parent DOM. I keep the div as display: none to start (when in the iframe), and I make it visible when I clone it in the parent. This all works fine, and here's a minimal snippet:
The parent (top.html):
<iframe src=foo.html></iframe>
The iframe (foo.html)
<html>
<HEAD>
<style>
#myid {
display: none;
}
</style>
</HEAD>
<body onload="onload()">
<script>
function onload() {
var div = document.getElementById("myid");
var newdiv = div.cloneNode(true);
var body = parent.document.getElementsByTagName("body")[0];
newdiv.id = "new" + div.id;
newdiv.style.display = "block";
newdiv.style.position = "absolute";
newdiv.style.top = "100px";
newdiv.style.left = "100px";
newdiv.style.width = "100px";
newdiv.style.height = "100px";
newdiv.style.background = "red";
body.appendChild(newdiv);
};
</script>
<div id=myid>
<p>foo
</div>
</body></html>
My issue that I would like to use internal css to define #myid WHEN THE DIV IS CLONED INTO THE PARENT. But, once the the div is cloned, it only references the CSS in the parent... I'm not (readily) able to modify the CSS of the parent.
Can I make the internal CSS "stick" to the div when it gets cloned?
For example, if I delete the line above:
newdiv.style.background = "red";
And instead add to the internal CSS:
background: red;
The red doesn't stay once I clone the div to the parent.
My only other solution is to just do it all inline, by changing the div, like:
<div id=myid style="background: red;">
And that works, its just that I have a lot of CSS and it's a mess to maintain that way.
My solution to this (from #charlietfl's suggestion) was to add:
newdiv.style.cssText = window.getComputedStyle(div).cssText;
to copy the computed CSS to the cloned div. Now I can add background: red to the internal CSS, and it is "stuck" to the clone.
The final solution is below:
<html>
<HEAD>
<style>
#myid {
/* Added style here */
background: red;
display: none;
}
</style>
</HEAD>
<body onload="onload()">
<script>
function onload() {
var div = document.getElementById("myid");
var newdiv = div.cloneNode(true);
var body = parent.document.getElementsByTagName("body")[0];
/* Copy styles here */
newdiv.style.cssText = window.getComputedStyle(div).cssText;
newdiv.id = "new" + div.id;
newdiv.style.display = "block";
newdiv.style.position = "absolute";
newdiv.style.top = "100px";
newdiv.style.left = "100px";
newdiv.style.width = "100px";
newdiv.style.height = "100px";
body.appendChild(newdiv);
};
</script>
<div id=myid>
<p>foo
</div>
</body></html>

jQuery function that returns when a div touches another div upon scroll

how can I give an alert when one div hovers over another div upon scroll? here is a working example,
http://jsfiddle.net/uprosoft/Ek5Gy/267/
I cant find a jQuery code to go after though in-order to give an alert.
Code:
HTML
<div id="container">
<div id="div1">test</div>
<br>
<div id="div2"> another test</div>
</div>
CSS
#div1{
background: green;
position: fixed;
width: 100%;
}
#div2{
background: yellow;
position: relative;
width: 100%;
margin-top: 100px;
}
#container{
height: 1000px;
}
JQUERY ???
/* what jquery code goes here? to alert when the yellow div touches the green div upon scroll? */
Something like that should work:
$(window).scroll(function() {
var div1 = $("#div1");
var div2 = $("#div2");
var div1_top = div1.offset().top;
var div2_top = div2.offset().top;
var div1_bottom = div1_top + div1.height();
var div2_bottom = div2_top + div2.height();
if (div1_bottom >= div2_top && div1_top < div2_bottom) {
// overlapped
}
});​
DEMO: http://jsfiddle.net/Ek5Gy/280/
I know the question is for Jquery but either way, the same done with vanilla JS
function didDiv1TouchedDiv2() {
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
// Guard
if (div1 === undefined || div2 === undefined) return;
var div1Rect = div1.getBoundingClientRect();
var div2Rect = div2.getBoundingClientRect();
// We need to add the offsetHeight in order to include padding and border of element and get excact position
return div1Rect.top >= div2Rect.top + div2.offsetHeight;
}
window.addEventListener("scroll", didDiv1TouchedDiv2);

Set absolute height (offsetHeight) of HTML containers that use CSS padding, margin and border by Javascript

I want to do something like setting offsetHeight (offsetHeight is a read only property) - fit 3 div ("d1", "d2", "d3") into one container ("c"):
<!DOCTYPE HTML>
<html>
<body>
<style type="text/css">
.c {
background-color:#FF0000;
overflow:hidden;
}
.d {
left:10px;
border:9px solid black;
padding:13px;
margin:7px;
background-color:#FFFF00;
}
</style>
<div class="c" id="c">
<div id="d1" class="d">text text text</div>
<div id="d2" class="d">text text text</div>
<div id="d3" class="d">text text text</div>
</div>
<script type='text/javascript'>
var h=600;
var hd = Math.floor(h/3);
var c = document.getElementById("c");
var d1 = document.getElementById("d1");
var d2 = document.getElementById("d2");
var d3 = document.getElementById("d3");
c.style.height=h +"px";
d1.style.height=hd +"px";
var hd2 = (2 * hd - d1.offsetHeight) +"px";
d1.style.height=hd2;
d2.style.height=hd2;
d3.style.height=hd2;
</script>
</body>
</html>
but - first: the boxes doesn’t fit perfect :-( and secondly the style is bad. Do you have a idea how to fit the 3 div ("d1", "d2", "d3") into one container ("c")?
=> also I dont know how to read the css properties "padding" and "margin"
alert(d1.style.paddingTop);
doesn't work (maybe because it is defined by css-class and not direct)
Thank you :-)
Best regards Thomas
Which browser your using and what DOCTYPE you have determines the default box model for block elements. Usually, the default is content-box, which means that the padding, border, and margin all add to the height/width, so you'll need to factor that into your calculations if you have the box model as content-box.
Another options is, you can change the box model to border-box using the box-sizing CSS property. This means that the padding and border are included in the height and width, and only the margin adds to them. In my opinion, this box model is usually a more convenient one for doing what I want, so I usually end up switching.
Reference:
https://developer.mozilla.org/En/CSS/Box-sizing
https://developer.mozilla.org/en/CSS/box_model
After some testing I figure out this solution:
(works with: Opera, Firefox and Google Chrome)
(box-sizing: doesn't work on Firefox when used JavaScript?!)
<!DOCTYPE HTML>
<html>
<body>
<style type="text/css">
.c {
background-color:#FF0000;
overflow:hidden;
margin:0px;
padding:0px;
}
.d {
left:10px;
border:13px solid black;
padding:7px;
margin-bottom:13px;
margin-top:4px;
background-color:#FFFF00;
}
</style>
<div class="c" id="c">
<div id="d1" class="d">text text text</div>
<div id="d2" class="d">text text text</div>
<div id="d3" class="d">text text text</div>
</div>
<script type='text/javascript'>
///////////////////////////////////////////
// see: http://stackoverflow.com/questions/1601928/incrementing-the-css-padding-top-property-in-javascript
function getStyle(elem, name) {
if (elem.style[name]) {
return elem.style[name];
}
else if (elem.currentStyle) {
return elem.currentStyle[name];
}
else if (document.defaultView && document.defaultView.getComputedStyle) {
name = name.replace(/([A-Z])/g, "-$1");
name = name.toLowerCase();
s = document.defaultView.getComputedStyle(elem, "");
return s && s.getPropertyValue(name);
}
else {
return null;
}
}
///////////////////////////////////////////
var c = document.getElementById("c");
var d1 = document.getElementById("d1");
var d2 = document.getElementById("d2");
var d3 = document.getElementById("d3");
var paddingY = parseInt(getStyle(d1, 'paddingTop'),10) + parseInt(getStyle(d1, 'paddingBottom'), 10);
var marginTop = parseInt(getStyle(d1, 'marginTop'),10);
var marginBottom = parseInt(getStyle(d1, 'marginBottom'),10);
var marginMax = Math.max(marginTop, marginBottom);
var borderY = parseInt(getStyle(d1, 'borderTopWidth'),10) + parseInt(getStyle(d1, 'borderBottomWidth'), 10);
var h=600;
var count=3;
var hd = Math.floor((h-marginMax*(count-1) - marginTop - marginBottom - (paddingY + borderY) *count) / count) ;
c.style.height=h +"px";
d1.style.height=hd +"px";
d2.style.height=hd +"px";
d3.style.height=hd +"px";
</script>
</body>
</html>

Categories