window scroll don't work properly - javascript

this is my code JS
var elem3 = document.createElement('DIV');
elem3.setAttribute('id', 'eye');
elem3.style.display = "block";
elem3.style.width = "100px";
elem3.style.height = "100px";
elem3.style.zIndex = "301";
elem3.style.position = "absolute";
elem3.style.top = "0px";
elem3.style.left = "0px";
document.body.appendChild(elem3);
var danger, up = 0;
window.onscroll = function(e) {
up += 10;
document.getElementById('eye').style.top = up + "px";
}
function check() {
danger = setInterval(function() {
if (document.getElementById('eye').style.top >= 2000 + "px") {
location.href = "http://www.google.com";
clearInterval(danger);
}
})
};
check();
I want to create a div (eye) and with scroll I want that this div fall by 10px.1 scroll=10px, 10 scroll=100px. If the top of eye is greater then 2000px this will redirect the page. But this don't work because when I begin scroll, the page redirect automatically and the div don't scroll to 2000px.

if (document.getElementById('eye').style.top>=2000+"px"){
That check is wrong, the check is a string comparison, not a number comparison.
You should be using parseInt to get the number value of the position.
if (parseInt(document.getElementById('eye').style.top,10)>=2000) { ...
Why are you checking the style when the variable up should hold the value?
if (up>=2000){ ...

Don't use window.onscroll=function(e){up+=10;document.getElementById('eye').style.top=up+"px";}
1) use scrollTop and added delay in setInterval.
2) Your "if" not work, use integer instead of string
Try this:
var elem3=document.createElement('DIV');
elem3.setAttribute('id','eye');
elem3.style.display="block";
elem3.style.width="100px";
elem3.style.height="100px";
elem3.style.zIndex="301";
elem3.style.position="absolute";
elem3.style.top="0px";
elem3.style.left="0px";
document.body.appendChild(elem3);
var danger, up=0;
window.onscroll=function(e){
up = window.scrollTop() + 10; //or `up = window.scrollTop();`
document.getElementById('eye').style.top = up +"px";
};
function check(){
danger = setInterval(function(){
if (parseInt(String(document.getElementById('eye').style.top).replace(/[a-zA-Z]/g)) >= 2000){
location.href="http://www.google.com";
clearInterval(danger);
}
}, 100);//Added delay
};
check();

Related

Understanding Functions and the semantics

Okay, Please be gentle I am learning Javascript.
I have two buttons (HTML5 <button> tags) they are both set to call the same function, In that function is two other functions (show + hide), Now, I am wondering if this is correct, i.e If i click on button hide, it calls function visibility, which then calls the function hide and hides everything defined in this function, including the original buttons. But if i click on button show, it hides the original content and displays extra content, with more buttons.(clickable process throughout)Or is it possible to call these functions separately within this function, For example:
function visible() {
function show() {
slide = document.getElementById('side');
pos = 0;
move = setInterval(slider, 1000/60);
slide1 = document.getElementById('main');
pos1 = 100;
move1 = setInterval(slider1, 1000/60);
document.getElementById('welcomer').style.display = 'none';
document.getElementById('welcome').style.display = 'none';
function slider() {
if (pos == 20) {
clearInterval(move);
}else {
pos++;
slide.style.display = 'block';
slide.style.width = pos + '%';
}
}
function slider1() {
if (pos1 == 80) {
clearInterval(move1);
}else {
pos1--;
slide1.style.width = pos1 + '%';
}
}
}
function hide() {
slide = document.getElementById('side');
pos = 0;
move = setInterval(slider, 1000/60);
slide1 = document.getElementById('main');
pos1 = 100;
move1 = setInterval(slider1, 1000/60);
document.getElementById('welcomer').style.display = 'none';
document.getElementById('welcome').style.display = 'none';
function slider() {
if (pos == 20) {
clearInterval(move);
}else {
pos++;
slide.style.display = 'block';
slide.style.width = pos + '%';
}
}
function slider1() {
if (pos1 == 80) {
clearInterval(move1);
}else {
pos1--;
slide1.style.width = pos1 + '%';
}
}
}
document.getElementById('vis').addEventListener('click', show());
document.getElementById('invis').addEventListener('click', hide());
}
Or is it semantically correct not to have nested functions, Instead to have the two separate functions, and call the functions separately onclick. For example:
function show() {
slide = document.getElementById('side');
pos = 0;
move = setInterval(slider, 1000/60);
slide1 = document.getElementById('main');
pos1 = 100;
move1 = setInterval(slider1, 1000/60);
document.getElementById('welcomer').style.display = 'none';
document.getElementById('welcome').style.display = 'none';
function slider() {
if (pos == 20) {
clearInterval(move);
}else {
pos++;
slide.style.display = 'block';
slide.style.width = pos + '%';
}
}
function slider1() {
if (pos1 == 80) {
clearInterval(move1);
}else {
pos1--;
slide1.style.width = pos1 + '%';
}
}
}
function hide() {
slide = document.getElementById('side');
pos = 0;
move = setInterval(slider, 1000/60);
slide1 = document.getElementById('main');
pos1 = 100;
move1 = setInterval(slider1, 1000/60);
document.getElementById('welcomer').style.display = 'none';
document.getElementById('welcome').style.display = 'none';
function slider() {
if (pos == 20) {
clearInterval(move);
}else {
pos++;
slide.style.display = 'block';
slide.style.width = pos + '%';
}
}
function slider1() {
if (pos1 == 80) {
clearInterval(move1);
}else {
pos1--;
slide1.style.width = pos1 + '%';
}
}
}
Or is it possible, for the button hide, do i just create an array, with every ID/Class Element i want to hide, call it with the onclick on the button to hide and then change the style to display: none; for all elements in that array?.
And vice versa for the divs i would create with button show?
Now i understand alot of this can be deemed opinionated, So the reason i am asking is this: I want to know which would be the quickest method using vanilla javascript, which way would shorten the amount of code and reduce loading time, with the best possible outcome based on facts.
Please note I have had to write this code with pretty much zero knowledge as i am learning Javascript, These are primarily for example, and both show/hide do the exact same thing for now, ultimately the show function will create more divs and content etc.
Having nested functions is perfectly acceptable, and often desirable or even necessary. The syntax would be as follows for doing so :
function base_function(){
this.function_1 = function(){};
this.function_2 = function(){};
}
This defines a function constructor with two values... function_1 and function_2. You could then call either of them using the following
var base = new base_function();
base.function_1();
Now, if you only need to reference those child functions within the scope of the base_function, something like the following would suffice.
function base_function(){
function child_function_1(){}
function child_function_2(){child_function_1();}
}
Think of function as it is in js, a datatype, like a string or numeric type. You can pass it to variables, reference it later on in code, pass it as a callback (like in setTimeout, you pass the reference to the function as a varaible. i.e. setTimeout(function_1,1000) rather than setTimeout(function_1(),1000)). You can also declare functions using var function_1 = function(){} because of this (and is my preferred method).
Because of the way javascript handles functions, you can do some interesting and super cool stuff with them - such as closures or IIFYs! Here is a great explanation of these and how to use them!
To answer your question, I would suggest going with the first route, while retaining a variable inside the function referencing the content you want to display/hide. Even if it means you need to write a few extra lines, it makes the code much more readable when you keep things modular, and readability really is king in most circumstances.
Something like this
var Vis_Controller = function(content){
this.content = content;
this.hide = function(){
content.style.display = "none";
}
this.show = function(){
content.style.display = "block";
}
}
window.addEventListener("load", function(){
var content = document.getElementById("content");
var button_show = document.getElementById("button-show");
var button_hide = document.getElementById("button-hide");
var vis_controller = new Vis_Controller(content);
button_show.addEventListener("click",vis_controller.show);
button_show.addEventListener("click",vis_controller.hide);
});

Fading out in Javascript

Hey I'm new to javascript and I'm working on a small chat program right now.
I've got all the chatlogs (global& private and stuff..) but i want to add a button which can make (most of) the elements of these little 'clients' fade out and in, so that you dont have to see ALL of them at one time, just the ones you want.
The (relevant) code with the example element mess1:
h=0;
newroom = function (roomname) {
//create new container
var div = document.createElement('div');
div.className = 'container';
//new text input
var mess = document.createElement('input');
mess.type = 'text';
mess.id = 'mess1' + i;
div.appendChild(mess);
//minimizer button
var min = document.createElement('input');
min.type = 'button';
min.value = 'Minimize chat';
min.id = 'min' + i;
div.appendChild(min);
document.body.appendChild(div);
document.getElementById("min" + h).addEventListener("click", function (){
//this is where the magic happens
}
h++;
};
I've tried document.getElementById("mess1" + h).style.visibility = 'hidden';, but that just makes the element disappear, leaving a big ugly blank space behind.
I thought document.getElementById("mess1" + h).fadeOut('slow'); would fix that, but it just doesn't do anything...
Thanks in advance for your answers
function fadeout(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
first of all I will recommend to use jQuery, it will make your life much more easy. In jQuery, you can fade the element and then remove it like this
$("#mess1" + h).fadeOut('slow',function(){
$("#mess1" + h).remove();
});
It will first fade the element and will then remove it from node if required
You can use
document.getElementById("mess1" + h).style.display= 'none';
it will hide element without empty space. But if you whant to hide element with animation you can use eq. this jquery:
$("#mess1" + h).hide('slow')
or eq. 'fast' - as parameter

Div with a simple variable height

So, I want to make a div that has the height of a value I'm going to get from my database. To make it better do understand, the value is a the number of times a client has bought in the website. I'm thinking of a way to make my div go up as the value go up.
Something like this:
var divHeight = numberOfValues;
numberOfValues = heightOfDiv; (div's height property)
if (numberOfValues == 0) {
divHeight = 0;
} else {
divHeight = numberOfValues + 10;
}
The logic is to have my div increase in 10px for every value number. So if the value is 10 the height should be 100px.
What is the best way for me to achieve this solution? Is it as simple as I think? (Simple != easy).
<?php
$numberOfPurchases = getNumberOfPurchases(); // call the function that queries the database
?>
<script>
var defaultDivHeight = 10;
var purchaseDiv = document.getElementById('purchaseDiv');
if (<?= numberOfPurchases; ?> > 0)
{
purchaseDiv.style.height = <?= numberOfPurchases; ?> * defaultDivHeight + 'px';
}
else
{
purchaseDiv.style.height = defaultDivHeight + 'px';
}
</script>
I suggest looking into using PDO in PHP for querying the database.
<script>
var divHeight = numOfVisits * 10;
var divDisplay = document.getElementById("display");
if(divHeight>0)
divDisplay.style.height = divHeight + "px";
else
divDisplay.style.height = "1px";
</script>

Javascript div fade in not working using setInterval

I'm trying to make a div containing a number of pictures to fade in but its not working and I don't know why. I believe that the inverval is not even being called. The div's opacity is set to 0.0 This is the code:
var movies = getElementById("movies");
var apparence = function(){
if(movies.style.opacity < 1.0){
movies.style.opacity = movies.style.opacity + 0.1;
} else { clearInterval(timer);
}
}
var timer = window.setInterval(apparence, 1000);
Thank you very much.
To set your movies var, you need to call:
document.getElementById('movies');
The way you are attempting to increment opacity didn't work, so I've updated your example.
New Code:
var movies = document.getElementById("movies");
var opacity = 0.1;
var apparence = function(){
if(opacity <= 1.0) {
movies.style.opacity = opacity;
} else {
clearInterval(timer);
}
opacity += 0.1;
}
var timer = window.setInterval(apparence, 1000);
JS Fiddle:
http://jsfiddle.net/onov6cq4/1/
Here is your problem
Problem1:
If you have defined your css using
#movies {
opacity: 0.0;
}
then document.getElementById().style.opacity is empty since it takes from inline style i.e. <div id="movies" style="opacity: 0.0">
Problem 2:
movies.style.opacity = movies.style.opacity + 0.1;
movies.style.opacity returns a string so you are basically appending string which results in 0.10.1 and so on. You need to do parseFloat! The attached fiddle will solve your problem
Code:
var moviesOp = document.getElementById('movies').style.opacity;
function apparence(){
console.log('interval called with op = ' + moviesOp);
if(moviesOp < 1.0){
moviesOp = parseFloat(moviesOp, 10) + 0.1;
} else {
clearInterval(timer);
}
}
var timer = setInterval(apparence, 1000);
<div id="movies" style="opacity: 0.0">
JSBin With Inline Style
If you want to use in css and not inline then use getComputedStyle. This i tried and works as u wanted
var movies = document.getElementById('movies');
function apparence(){
var moviesOp = getComputedStyle(movies).getPropertyValue('opacity');
console.log('interval called with op = ' + moviesOp);
if(moviesOp < 1.0){
movies.style.opacity = parseFloat(moviesOp, 10) + 0.1;
} else {
clearInterval(timer);
}
}
var timer = setInterval(apparence, 1000);
Non Inline jsBin

how to check if the scrollbar has reached at the end of div?

function yHandler () {
var show = document.getElementById('show');
var contentHeight = show.offsetHeight;
var yOffset = show.pageYOffset;
var y = yOffset + show.innerHeight;
if(y >= contentHeight) {
alert("ok")
}
}
show.onscroll = yHandler;
how to check if the scrollbar has reached the end of div?
Some code for you to work on:
var scroll = document.getElementById('scroll');
var content = document.getElementById('content');
scroll.onscroll = function(){
var total = scroll.scrollTop + scroll.clientHeight;
if(total == content.clientHeight)
alert('Reached bottom!');
}
http://jsfiddle.net/EY6qP/
Thor's method works perfectly well (+1), but you could also rely on scrollHeight.
(function(scroll){
scroll.onscroll = function(){
if (scroll.scrollTop + scroll.clientHeight == scroll.scrollHeight) {
console.log('hither!');
}
}
})(document.getElementById('scroll'));
Use scrollHeight, scrollTop and clientHeight attributes to detect the scroll bar reached bottom end or not.
function handleScroll() {
var div = document.getElementById("div-id");
if(Math.abs(Math.round(div.scrollHeight - div.scrollTop) - div.clientHeight) > 3) {
console.log("Scroll bar reached bottom end");
return true;
}
return false;
};

Categories