removeChild Syntax - I Need A Pair of Experienced Eyes - javascript

I am using the removeChild method for the first time. I have use javascript to modify my navbar so that it changes to fixed position and and scroll with the user. This causes the content of the body div to jump up slightly when this happens. As a result, I have managed to insert a red box (it will later be white) to take up the extra space when the navbar's position changes.
I need that red box to be removed when the user scrolls back to the top but I can't seem to get the remove child function to fire. If somebody could take a look and point me in the right direction that would be swell!
code (relevant code section is in bold):
var fillerState = false;
// fixed positioning on scroll property for taskbar:
window.addEventListener('scroll', function (evt) {
var distance_from_top = document.body.scrollTop;
if (distance_from_top <= 80) {
document.getElementById("navBar").style.position = "static";
document.getElementById("navBarList").style.borderBottom = "solid black 4px";
document.getElementById("navBar").style.borderTop = "initial";
var myCollection = document.getElementsByClassName("navBarLink");
var collectionLength = myCollection.length;
for(var i = 0; i < collectionLength; i++){
myCollection[i].style.borderTopLeftRadius = "1em";
myCollection[i].style.borderTopRightRadius = "1em";
myCollection[i].style.borderBottomLeftRadius = "initial";
myCollection[i].style.borderBottomRightRadius = "initial";
}
// stops loads of boxes from forming:
**if(fillerState == true){
var parentRemove = document.getElementById("bodyDiv");
var fillerBoxRemove = document.getElementById("fillerBox");
parentRemove.removeChild(fillerBoxRemove);
fillerState = false;
alert(fillerState);**
}
}
else if(distance_from_top > 80) {
document.getElementById("navBar").style.position = "fixed";
document.getElementById("navBar").style.top = "0px";
document.getElementById("navBar").style.borderTop = "solid black 4px";
document.getElementById("navBarList").style.borderBottom = "initial";
var myCollection = document.getElementsByClassName("navBarLink");
var collectionLength = myCollection.length;
if(fillerState == false){
// sets filler element so that the page doesn't bounce:
var filler = document.createElement("div");
filler.style.width = "200px";
filler.style.height = "80px";
filler.style.backgroundColor = "red";
filler.style.id = "fillerBox";
//defines where the new element will be placed:
var parent = document.getElementById("bodyDiv");
var brother = document.getElementById("leftColumn");
parent.insertBefore(filler,brother);
fillerState = true;
}
for(var i = 0; i < collectionLength; i++){
myCollection[i].style.borderTopLeftRadius = "initial";
myCollection[i].style.borderTopRightRadius = "initial";
myCollection[i].style.borderBottomLeftRadius = "1em";
myCollection[i].style.borderBottomRightRadius = "1em";
}
}
});

as squint pointed out, when you're making the element, you're setting it's style.id, which is not right.
Change:
filler.style.id = "fillerBox";
To:
filler.id = "fillerBox";
And your code will work.
Alternatively, you can do as others have suggested and create the box in the html itself, set it to a class that has no display, then change it's class. Not only easier, but also stops you from creating and destroying. less resource intensive that way.

Related

compare pixel postition via code on javacript

i have a problem. i'm using javascript and i'm always trying to make a faster code.
so i create an app that check the pixel position.
if your pixel pointer(red) is in the target position, the target make an action.. just press (t) to see it down
But when cross the red tile on loop to create a lot of places akk "if" dont work.
I wish he alert everytime the red takes the blue.
have any trigger to make check colision to the first object to another??
how to make a lot of if to be checked automated?
<body>
</body>
<script>
//ok... trying again
document.addEventListener('keydown', function(e) {
if (e.keyCode == 84) {
e.preventDefault();
check();
}
})
var position = 0
let a = document.createElement("div")
a.style.backgroundColor = "red"
a.style.height = '1px'
a.style.width = '1px'
a.style.top = position
a.style.position = "absolute"
document.body.append(a)
for (let index = 0; index < 10; index++) {
let x = index
//b = new b all the time
let b = document.createElement("div")
b.style.backgroundColor = "blue"
b.style.height = '1px'
b.style.width = '1px'
b.style.position = "absolute"
b.style.top = Math.floor(Math.random(10 - 0) * 100)
document.body.append(b)
//remember b = nem b on let all the time
function check(){
a.style.top = position++
if (a.style.top === b.style.top ){
alert("its ok")
}
}
}
</script>
help

Changing the background color of an element sets websites text to the color

Im trying to make a javascript bookmark using The code I wrote. It's supposed to add an element (in this case it adds a div. The div is as large as the size of innerHeight and innerWidth. The height shrinks by a few pixels every 250 milliseconds. It works on CodePen, but when I try it on another website, it changes the entire HTML of the page to "white" (which is the background color of the added element). Here is the code:
var falseLoaderContainer = document.getElementsByTagName("html")[0];
falseLoaderContainer.innerHTML += `<div id="falseLoader"></div>`;
var falseLoader = document.getElementById("falseLoader");
falseLoader.style.position = `absolute`;
falseLoader.style.width = `${window.innerWidth}px`;
falseLoader.style.height = `${window.innerHeight}px`;
falseLoader.style.bottom = `0px`;
falseLoader.style.left = `0px`;
falseLoader.style.backgroundColor = `white`;
var falseLoaderHeight = falseLoader.style.height.replace(/px/g, "");
var updateFalseLoader = setInterval(function () {
falseLoaderHeight *= 1;
falseLoaderHeight -= Math.ceil(Math.random() * 4);
falseLoader.style.height = falseLoaderHeight + "px";
if (falseLoaderHeight <= 0) {
clearInterval(updateFalseLoader);
}
}, 250);
Try:
var element = document.getElementById("id");
element.setAttribute("style", "background-color: COLOR;");
or:
var element = document.getElementBYId("id");
element.style = "background-color: COLOR;");
Hope this helps!

createElement: How to make this cross-browser - works in IE10

I have the following javascript which is a loader that is triggered and created when the page is idle. It basically shows whilst the next navigated page is loading. The script resides on the (ASP.NET) master page and an Ajaxified user control.
I need to make the code cross-browser but not sure what the offender is.
It only works happily in Trident (only tested IE9 & 10) - not in Webkit or Gecko.
I'm not sure if it's a notation issue or if the page life cycle for Chrome and Safari don't ever declare themselves as "!= complete" thus not triggering the condition.
I'd also prefer to keep this a pure Javscript solution - no jQuery.
Thanks
loader = 0;
if (window.location.href.indexOf("Login.aspx") < 0) {
setInterval(function () {
if (document.readyState != 'complete') {
document.documentElement.style.overflow = "hidden";
var navLoader = document.createElement("div");
var loaderText = document.createElement("div");
var loaderImg = document.createElement("div");
navLoader.id = "navLoaderDiv";
navLoader.className = "navLoader";
loaderImg.id = "loaderImg";
loaderText.id = "loaderText";
loaderImg.className = "loaderImg";
loaderText.className = "loaderText";
navLoader.appendChild(loaderImg);
navLoader.appendChild(loaderText);
loaderText.innerHTML = "Working on it";
var zedDepth = 99999;
navLoader.style.zIndex = zedDepth;
navLoader.style.background.image = "url(~/Images/loaderHalo2.png) 0 0 / 100% 100% no-repeat";
navLoader.style.position = "absolute";
navLoader.style.right = "0px";
navLoader.style.left = "0px";
navLoader.style.top = "25px";
navLoader.style.bottom = "0px";
if (loader == 0) {
document.documentElement.appendChild(navLoader);
loader = 1;
}
} else if (document.getElementById('navLoaderDiv') != null) {
document.getElementById('navLoaderDiv').style.display = "none";
document.documentElement.style.overflow = "hidden";
}
}, 1000)
}

How to Disable a CSS Property and Make It Invalid

Okay, so here is the concept. My HTML document has a button that onClick runs a Javascript function. On the web page there are two big divisions, and the purpose of the button is to swap the divisions' places. For example, the one that was on the left goes the right, and the one on the right to the left.
The problem is, the "left" CSS property has dominance over the "right" property, so if both the left and right properties are set to 0 on a div with a fixed width, it will go to the left. Therefore, I cannot get what is on the left over to the right because the "left" property is still present.
I need some way to make the left property invalid, as if I had never even set it so the div will go to the right.
The two divs are called "content" and "navigation" and here is my JS:
var order = 0;
var current;
var switchLayout = function() {
if(order === 0) {
current = document.getElementById('content');
current.style.position = 'absolute';
current = document.getElementById('navigation');
current.style.left = '0';
order = 1;
} else {
current = document.getElementById('content');
current.style.position = 'relative';
current = document.getElementById('navigation');
current.style.left = 'null';
current.style.right = '0';
order = 0;
}
}
Any help is appreciated. Thanks!
Dont do your css in Javascript. The easiest way to solve this is have two css classes
.left{
/* styling */
}
.right {
/* styling */
}
var switchLayout = function() {
var content = document.getElementById('content'),
nav = document.getElementById('navigation');
if (content.className === "left") {
content.className = "right";
nav.className = "left";
} else {
content.className = "left";
nav.className = "right";
}
}

Cancel XMLHttpRequest?

Good day there
I have a site where I have lots of 'tooltips'. These tooltips are created when hovered on a certain part of text. The tooltip is a div block which appears on top all the other content on site, and is removed when the cursor is moved away from the text. Now, this tooltip is spawned only when the text has <a rel> with 'tooltip' class. The tooltip fetches data from MySQL database with XMLHttpRequest and with the rel tag. This all works very well but I have a one little problem. Tooltip.php, which is the main script for fetching data from MySQL (8,809 lines), sometimes takes a while to respond. For example if I just quickly move my cursor through the site and the cursor accidently hovered for 0.05 secs a text with <a rel> text, it will generate a tooltip even if my cursor is not any longer on the text. I want some sort of check to check is the cursor still on the same <a rel> text, before creating the actual tooltip.
HTML:
A tooltip
Javascript:
function createTooltip(event)
{
var target = event.target || event.srcElement;
var str = target.rel || target.parentNode.rel;
if (str === "" || !str)
{
return;
}
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else // for older IE clients
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var link = document.getElementsByClassName('tooltip');
var oldTooltip = document.getElementsByClassName('object-tooltip'); // removing possible old tooltips...
for (var k = 0; k < oldTooltip.length; k++)
{
if (oldTooltip[k])
{
oldTooltip[k].remove();
}
}
for (var i = 0; i < link.length; i++)
{
if (str == link[i].rel)
{
var tooltip = document.createElement("div");
tooltip.setAttribute('class', 'object-tooltip');
tooltip.style.border = "solid 1px black";
tooltip.style.color = "white"; //"#99CC00";
tooltip.style.position = "fixed";
tooltip.style.width = "300px";
tooltip.style.left = event.clientX + 'px';
tooltip.style.top = event.clientY + 'px';
tooltip.style.padding = "5px 10px 5px 10px";
tooltip.style.margin = "-25px 0 0 60px";
tooltip.style.backgroundColor = "#0E0E0F";
tooltip.style.opacity = "0.9";
tooltip.style.display = "inline-block";
tooltip.style.zIndex = "100000";
tooltip.style.textDecoration = "none";
tooltip.style.textAlign = "left";
tooltip.innerHTML = xmlhttp.responseText;
link[i].parentNode.insertBefore(tooltip, link[i].nextSibling);
}
}
}
};
xmlhttp.open("GET", "./armory/tooltip.php?s="+str, true);
xmlhttp.send();
}
function moveTooltip(event)
{
var tooltip = document.getElementsByClassName('object-tooltip');
for (var i = 0; i < tooltip.length; i++)
{
tooltip[i].style.left = event.clientX + 'px';
tooltip[i].style.top = event.clientY + 'px';
}
}
function removeTooltip()
{
var tooltip = document.getElementsByClassName('object-tooltip'); // you can have only one tooltip active at time
for (var i = 0; i < tooltip.length; i++)
{
tooltip[i].remove();
}
}
I will not share tooltip.php for the sake of your time. It only gets the rel attribute and searches MySQL database with the attribute and prints data back. Is it possible to check is the cursor still on the same text, before creating the tooltip?
The best regards
Welp, based on your current code, you need to add, for instance, a variable outside of the scope of your existing createTooltip function to bind the xhr request to, let's call it, xmlhttp to be aligned with your existing code
var xmlhttp; //not in a function
Now add an event listener for the mouseout function on the .tooltip class, then abort the xhr request.
document.querySelectorAll('.tooltip').addEventListener('mouseout', function(){
xmlhttp.abort();
});
Now when the element with .tooltip triggers the mouseleave needless xmlhttprequests will be aborted.

Categories

Resources