I'm trying to resize a div when the size of the div is 50% to 100%. But when I try to console.log the current size of the div it just logs whitespace... Whats wrong?
window.onload = function() {
//declare vars
var fullbox = document.getElementById('box'),
minBut = document.getElementById('down');
minBut.onclick = function() {
if(fullbox.style.width == "50%") {
fullbox.style.width = "100%";
} else {
fullbox.style.width = "50%";
}
}
}
that could be the case when the width has not been initialized for that element before.
The second time it should be 50%.
tested with adding alert(fullbox.style.width);
FIDDLE
Related
I'm pretty new to JavaScript and trying to make my image from RGB to Grayscale while scrolling down and vise versa. I managed my image to get grayvalued when scrolling however I don't get back to the RGB image.
My code for JavaScript is:
let element = document.getElementById("image");
window.onscroll = function() {
var scrollLimit = 100;
if (window.scrollY >= scrollLimit) {
element.style.filter = 'grayscale(1)';
} else {
element.src = 'ttps://images.unsplash.com/photo-1542903660-eedba2cda473?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1170&q=80'
}
};
It's also public on https://jsfiddle.net/vdszymh7/139/
Maybe you have some suggestions how to dynamically change between these two modes.
What you're trying to achieve could be done by this way:
window.onscroll = function() {
var scrollLimit = 100;
if (window.scrollY >= scrollLimit) {
element.style.filter = 'grayscale(1)';
console.log('gray')
} else {
element.style.filter = 'none'
}
};
So I'm attempting to set up a rotating banner on my website (viewable at https://www.leapcraft.net) and I have a variable that gets the width of the element and should be offsetting the element not inside of the div by the number of pixels.
I've tried setting the values back to their original offset which fixes it.
var bannerStatus = 1;
var bannerTimer = 4000;
var element = document.getElementById("main-banner");
var positionInfo = element.getBoundingClientRect();
var o = positionInfo.width;
window.onload = function() {
bannerLoop();
}
var startBannerLoop = setInterval(function() {
bannerLoop();
}, bannerTimer);
function bannerLoop() {
if (bannerStatus === 1) {
document.getElementById("imgban2").style.opacity = "0";
setTimeout(function() {
document.getElementById("imgban1").style.right = "0px";
document.getElementById("imgban1").style.zIndex = "1000";
document.getElementById("imgban2").style.right = "-"+ o;
document.getElementById("imgban2").style.zIndex = "1500";
document.getElementById("imgban3").style.right = o;
document.getElementById("imgban3").style.zIndex = "500";
}, 500);
setTimeout(function(){
document.getElementById("imgban2").style.opacity = "1";
}, 1000);
bannerStatus = 2;
}
Expected Results: Rotating banner that is responsive to Width of device that is defined in style.css
Why you can't use css styles to rotate image? Look on my solution, maybe will be useful to you.
function bannerLoop() {
imgBanner[imgNum].style.opacity=1;
imgBanner[imgNum].style.WebkitTransitionDuration='';
imgBanner[imgNum].style.webkitTransform = '';
setTimeout(()=>{
imgBanner[imgNum].style.WebkitTransitionDuration='1s';
imgBanner[imgNum].style.webkitTransform = 'rotate(360deg)';
imgBanner[imgNum].style.opacity=0;
(imgNum<imgBanner.length-1)?imgNum++:imgNum=0
},3000)
}
And here is a working fiddle: https://jsfiddle.net/udtr659y/
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.
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";
}
}
I want to show a big Image when I press the small thumbnail. A simple Lightbox style script.
When I press the grey transparent overlay area around the image, the CSS and image is removed from view. This code is stripped down. Maybe missed something needed...
$(document).ready(function() {
$(".lightBobo").click(function(e) {
e.preventDefault(); // prevent to open link in new window
$(this).lightBobo();
});
});
jQuery.fn.lightBobo = function(e) {
if (e != undefined)
e.preventDefault();
return this.each(function() {
var img = new Image();
$(img).load(function() {
imgW = img.width;
imgH = img.height;
var overlay = $("<div />");
var container = $("<div />");
// Lots of css styling for <div> overlay and container image...
container.append(img); //add image to div
$("body").append(overlay); //add overlay to body
$("body").append(container); //add div to body
overlay.fadeIn("fast", function() {
container.show();
});
$(overlay).click(function() {
removeDivs();
});
function removeDivs() {
container.hide();
overlay.fadeOut("fast");
img = null;
container = null;
overlay = null;
openImgSrc = "";
}
});
});
}
The problem is IE(7) is not showing the image the second time I want to show it. I have to do a page reload to display the image again. It works in FF though.
When I use FireFox I can see in FireBug that the get appended to for each time I show the big image. And the "old" image get's display: none; After 20 times I show the big image, I have 40 elements of Overlay and Container(image).
I can't figure out how to rerun the lightBobo function when needed. So it workes in both IE and FF.
You should probably append the overlay and container just once when initialized, then just show/hide/append content when the user activates the modal.
Otherwise you need to do .remove() on each element ( = null is not enough ) when unloading, unless you want lots of dupes in the DOM.
I would do something like this:
(function($) {
var lightBobo = {
init: function() {
var self = this;
this.overlay = $('<div>').click(this.hide); // bind the click event just once
this.container = $('<div>');
// apply id's or styling
$(document.body).append(overlay,container);
}
hide: function(e) {
lightBobo.container.hide();
lightBobo.overlay.fadeOut('fast');
},
show: function() {
var img = new Image();
$(img).load(function() {
imgW = img.width;
imgH = img.height;
lightBobo.container.append(img); //add image to div
lightBobo.overlay.fadeIn("fast", function() {
lightBobo.container.show();
});
});
}
};
$(function() {
lightBobo.init(); // init the lightbox once
});
$.fn.lightBobo = function() {
return this.each(function() {
lightBoo.show.apply(this);
});
}
})(jQuery);
// bind the anchors here:
$(document).ready(function() {
$(".lightBobo").click(function(e) {
e.preventDefault(); // prevent to open link in new window
$(this).lightBobo();
});
});
I have found a solution. I changed lots of code. Specially the $(img).load(function() { ... } where I was having some problems. I dont really know WHY the load() function didnt want to kick the event more than one time. So I removed most code out of that function.
Remember the $(img).load(function() { ... } is for loading the image BEFORE finding its width and height. otherwise its 0.
$(document).ready(function() {
$(".lightBobo").click(function(e) {
if (e != undefined)
e.preventDefault();
$(this).lightBobo();
});
});
jQuery.fn.lightBobo = function(e) {
return this.each(function() {
var myClickedObj = $(this);
//check if we have a anchor or image tag
var src = "";
if (this.tagName.toLowerCase() == "a")
src = this.href.toLowerCase();
else if (this.tagName.toLowerCase() == "img")
src = this.src.toLowerCase();
else
return;
var winW = $(window).width();
var winH = $(window).height();
var docH = $(document).height();
if (docH < winH)
docH = winH;
//the semitransparant overlay over the whole page
var overlay = $("<div />")
.attr("class", "bobOverlay") //used as id for closing all overlays
.css("background", "#000")
.css("opacity", "0.8")
.css("display", "none")
.click(function() { hideAll(); })
$("body").append(overlay); //add overlay to body
var loadLeft = (winW / 2) - (100 / 2);
var loadTop = (winH / 2) - (20 / 2) + $(document).scrollTop();
overlay.fadeIn("fast");
//an element to hold our picture
var container = $("<div />");
container.attr("class", "bobOverlay");
container.hide();
var img = new Image();
$(img).load(function() {
var imgW = img.width;
var imgH = img.height;
container.append(this); //add the picture to the container
$("body").append(container); // add container to the body
container.fadeIn("fast"); //show container
})
.attr("src", src); //add the src to the image
function hideAll() {
$(".bobOverlay").fadeOut("fast");
}
function IsImage(filename) {
var ext = filename.split('.').pop().toLowerCase();
var allow = new Array("gif", "png", "jpg", "jpeg", "bmp");
if (jQuery.inArray(ext, allow) == -1) {
return false;
}
return true;
}
});
}
Sorry for the long code. And finding out the answer myself...