Variable not passing into function? - javascript

I tried to google this but couldn't find a solution. So the problem is I'm trying to execute something once if user window width is changed to specific width+-, however; the variable is undefined inside the function for some reason.
Here's the code:
jQuery(document).ready(function ($) {
var windowWidth = $(window).width();
var n = 1;
if(windowWidth >= 900) {
var tc = 3;
$(".debug").html(tc); // Making sure if user window width is 900 or more and tc is 3 on page load.
} else if (windowWidth <= 900) {
var tc = 2;
$(".debug").html(tc); // Making sure if user window width is 900 or less and tc is 2 on page load.
}
function liveWidthChange(){
var windowWidth = $(window).width();
$(".debug2").html("<b>current width:</b> " + windowWidth + " - <b>tc:</b> " + tc);
if (tc == 3 && windowWidth <= 900) {
// Shows how many times executed if activly changing browser width and the current value of tc
$(".debug").html("tc Value: " + tc);
var tc = 2;
}
}
// If the browser changes size
var RS = false;
$(window).resize(function() {
if (RS !== false) clearTimeout(RS);
RS = setTimeout(liveWidthChange, 200);
});
});
So if user has window width of 900 or more, it sets tc variable to 3, if user is resizing browser and it goes under 900, execute something.
Thanks in advance.

You need to declare tc in a place where all the functions will have access to it:
var windowWidth = $(window).width();
var n = 1;
var tc; // here, at the top.
Then you just need to remove the var in each location you set the value of tc.

I see several things.
You always redeclare the variable tc, instead you should move it on top
$(document).ready(function ($) {
var originalWidth = $(window).width();
var n = 1;
var tc = 2;
var MAX_WIDTH = 900;
[...]
You will be confused by naming two different variable with the same name:
In the ready block:
var originalWidth = $(window).width();
In the function:
var currentWidth = $(window).width();
You are using the operator '==' in order to compare integers, you should use '===' instead unless you know what you are doing.
x = "5"
>>> x == 5
true
>>> x === 5
false
In your condition you have
if(windowWidth >= 900) {} else if (windowWidth <= 900) {}
What if the windowWidth = 900, it will always go inside the first condition...
I beleive that you may want to use '<' or '>'

Related

Better way to get scroll Parameters?

So, I'm trying to get some parallax scrolls in my document. So I did:
window.onscroll = function() {scrollPost()};
function scrollPost () {
var i = window.scrollY;
blockShift(i);
console.log(i);
}
function blockShift (i){
var blockOne = document.querySelector(".block-1");
var blockTwo = document.querySelector(".block-2");
var y = i - 900
if (i < 980){
blockOne.style.transform = `translateY(${y/3}px)`
blockTwo.style.transform = `translateY(${y/-3}px)`
}
}
However, I wonder if there's a more accurate way to get numbers? One of the problem is that scrollY number is variable depending on screen size. I've also tried.
var x = window.screen.width;
var i = window.scrollY;
var number = Math.round(i/x);
Which gives me a 0.xxxxxxx number. How would I get something better?
Edit: this also works well
var x = window.screen.width;
var i = window.scrollY;
var a = i / x;
var numb = Math.round(a * 10) / 10;

Block change value of variable when refresh page in javascript

I have 2 variables name first and last. When window size is less than 768px, i want first = 1 and last = 5. And when window size is greater than 768px, first = 1 and last = 3. Here is my code.
var first = 1;
var last = 5;
window.onresize = function(){
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.getElementsByTagName('body')[0].clientWidth;
if (w <= 768){
first = 1;
last = 3;
}
if (w > 768){
first = 1;
last = 5;
}
}
It's worked. But when window size is 600px (less than 768px), i press F5 (refresh), first variable = 1 and last = 5 (these values are changed). I want when i press F5, if window less than 768px, its still 1 and 3. What can i do now? Help me. Thanks.
This is how it should be.
So now, we have one Function that set variables as per width of the Window.
We will call it two Times
When the page is loaded, you should Set Variables (First,Last) as per Size of window
When the page is Resized, you should Set Variables again.
var first = 1;
var last = 5;
function setVariables()
{
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.getElementsByTagName('body')[0].clientWidth;
if (w <= 768){
first = 1;
last = 3;
}
if (w > 768){
first = 1;
last = 5;
}
}
window.onresize = function(){
setVariables();
}
setVariables();
Just move your function into a separate function and reuse it on page loading:
function checkWidth(){
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.getElementsByTagName('body')[0].clientWidth;
if (w <= 768){
first = 1;
last = 3;
}
if (w > 768){
first = 1;
last = 5;
}
}
...
var first = 1;
var last = 5;
window.onresize = checkWidth;
window.onload = checkWidth;

How do I change a HTML ID with Javascript on page load after getting window size?

I am wondering how I can use Javascript to get a windows size and then set (really clear) an HTML ID with it.
I am currently working on a site that has a "default" navigation ID of "access" which I want to blank out if the windows size is less than 800 px wide.
This is the page I am working on and if the ID is cleared I can then setup the mobile navigation to work with bootstrap.
`window.onload = function() {
var w = window.innerWidth;
if(w < 800) {
document.getElementById('access').removeAttribute('id');
}
}
window.onload = function() {
var w = window.innerWidth;
if(w < 800) {
document.getElementById('access').removeAttribute('id');
}
}
window.onresize = function() {
var w = window.innerWidth;
if(w < 800) {
document.getElementById('access').removeAttribute('id');
}
}
Use
var w = window.innerWidth;
to get the width of the page.
and then,
window.onload = function() {
if(w < 800) {
document.getElementById('access').removeAttribute('id');
}
}
You probably want to add this functionality in resize too.
EDIT: put the code in window.onload
Based on the comment,
window.onload = function() {
var accessElem = document.getElementById('access');
var updateAccess = function() {
var w = window.innerWidth;
if(w < 800) {
accessElem.removeAttribute('id');
}
else {
accessElem.setAttribute('id', 'access');
}
};
window.onresize = updateAccess; // call updateAccess on resize
updateAccess(); // call once on load to set it.
};
Also, in my opinion, adding/removing id is not a great idea.

making a function works on specific widths

I am trying to make this function works only when the screen size is above 1024px.
//Parallax background image
var velocity = 0.5;
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};$(window).bind('scroll', update); update();
Here is what I have tried to do:
//Parallax background image
var velocity = 0.5;
$(window).on("ready resize", function() {
if ($(window).width() < 770) {
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};});$(window).bind('scroll', update); update();
I really don't know what I am doing wrong...
You haven't stated what the problem you're coming across is. If it's "my code doesn't work", then perhaps you should check your syntax first. Your braces are messed up.
//Initialize velocity and empty update function
var velocity = 0.5;
var update = function () {};
//When window is ready (content loaded) OR resized, execute the following function
$(window).on("ready resize", function () {
if ($(window).width() >= 1024) { //Check if window width is 1024px wide or larger
update = function () { //Set update to run this function when executed.
var pos = $(window).scrollTop(); //Get scrollbar position https://api.jquery.com/scrollTop/
//For each element with 'parallax' class, execute the following function
$('.parallax').each(function () {
var $element = $(this); //Get the current parallax-classed element
var height = $element.height(); //Save the current height of this element
//Set the CSS of this parallax-classed element set the background position
$(this).css('background-position', '40% + ' + Math.round((height - pos) * velocity) + 'px');
});
};
} else { //Execute if screen width is < 1024px
update = function () {}; //Set update to do nothing
}
});
//When window is scrolled through, run the update function
$(window).bind('scroll', update);
//update();
Last line is unnecessary, as resize will handle function value, and scroll will handle the execution.
You were missing a + or - within the background-position setting.
So for example, if the result of your Math.round() was "30", then Javascript would interpret that line as $(this).css('background-position', '40%30px'); which obviously would cause issues. I'm sure you wanted it to say something like $(this).css('background-position', '40% + 30px');.

Trigger points for javascript depending on viewport size

So, I'm coding up a site that has certain events triggering as you scroll down the page. I want the events to be triggered when the relevant element hits a point just around a quarter of the way down the viewport.
However, this trigger point is obviously different for different sized viewports. I've worked out how to get this trigger point calculated, but I haven't found a way to get the position of a div relative to the top of the viewport/page.
I am trying to use .offset(), which I could combine with getPageScroll() to find the right point, but I can't figure out what on earth to do with the array that it returns. I've also tried popping it in a variable and using that with the syntax I have below (as used on the jquery.com documentation), but it's patently wrong, and returned Undefined in the console.
I am pretty new to both Javascript and jQuery, and to any actual programming in general, so please excuse any stupidity. If I'm doing this all backwards, that's totally a valid answer too! Please just point me in the correct direction if that's the case.
I've coded it up like this so far. The actual effects are only placeholders for now - I'm just trying to get the basic framework working:
// getPageScroll() by quirksmode.com - adapted to only return yScroll
function getPageScroll() {
var yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {
yScroll = document.documentElement.scrollTop;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
}
return yScroll
}
// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
var windowHeight
if (self.innerHeight) { // all except Explorer
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowHeight = document.body.clientHeight;
}
return windowHeight
}
var containers = $('div.container');
var element_1 = $('#part_one');
var element_2 = $('#part_two_1');
var element_3 = $('#part_two_2');
var element_4 = $('#part_two_3');
var element_5 = $('#part_two_4');
var element_6 = $('#part_three');
var element_7 = $('#part_four');
var element_8 = $('#part_five');
var docHeight = $(document).height();
$(window).scroll(function() {
var offset = offset();
var docHeight = $(document).height();
var pageBottom = getPageScroll() + getPageHeight();
var quarterPoint = getPageScroll()+((pageBottom-getPageScroll())/4)
var halfwayPoint = getPageScroll()+((pageBottom-getPageScroll())/2)
var threeQuarterPoint = pageBottom-((pageBottom-getPageScroll())/4)
var triggerPoint = quarterPoint-(getPageHeight/10)
if (triggerPoint < element_1.offset.top){
containers.stop().animate({backgroundColor: "white", color: "#aaa"}, 50);
element_1.stop().animate({backgroundColor: "#ffa531", color: "white"}, 300, function(){
$(this).children().stop().animate({opacity: "1"}, 300);
});
};
if (triggerPoint > element_2.offset.top){
containers.stop().animate({backgroundColor: "white", color: "#aaa"}, 50);
element_2.stop().animate({backgroundColor: "#d900ca", color: "white"}, 300, function(){
$(this).children('img').stop().animate({opacity: "1"}, 300);
});
};
if (triggerPoint > element_3.offset(top)){
containers.stop().animate({backgroundColor: "white", color: "#aaa"}, 50);
element_3.stop().animate({backgroundColor: "#d900ca", color: "white"}, 300);
};
and so on and so forth, for somewhere between 8 and 12 trigger points.
Any help would be greatly appreciated!
Couple things i see here:
var offset = offset(); // i don't believe this is a global function.
if (triggerPoint < element_1.offset.top) { // offset needs to be offset(), its a function not a property

Categories