Execute javascript for certain screen size - javascript

I have a javascript function that I need modified for certain screen sizes, though I've tried "if (screen.width <= 960) {... " and "if (window.width <= 960) {..." , only the part after "else" get's executed, like it's not even looking at the screen width I'm placing in the parenthesis.
Here is my function ( I know it's poorly written, but I'm new to javascript):
$(document).ready(function(){
var numberofscroll = 0;
var lastScrollTop = 0;
$("#home").scroll(function(){
var st = $(this).scrollTop();
(st > lastScrollTop) ? numberofscroll++ : numberofscroll--;
console.log(numberofscroll);
console.log(lastScrollTop);
console.log(st);
if (numberofscroll<2){
change_background2(numberofscroll);
}
else if (numberofscroll<3){
change_background3(numberofscroll);
}
else if (numberofscroll<4){
change_background4(numberofscroll);
}
lastScrollTop = st;
});
function change_background2(numberofscroll){
var i;
for (i = 2) {
$("#home").css("background-position","0 -652px");
}
}
function change_background3(numberofscroll){
var i;
for (i = 3) {
$("#home").css("background-position","0 -1326px");
}
}
function change_background4(numberofscroll){
var i;
for (i = 4) {
$("#home").css("background-position","0 -1978px");
}
}
)};

Corrections:
Changed all the for to ifs.
Corrected the parentheses.
Assigned a temp variable to ternary operation.
Changed all the i to numberofscroll
I believe the corrected JavaScript is:
$(document).ready(function () {
var numberofscroll = 0;
var lastScrollTop = 0;
$("#home").scroll(function () {
var st = $(this).scrollTop();
n = (st > lastScrollTop) ? numberofscroll++ : numberofscroll--;
console.log(numberofscroll);
console.log(lastScrollTop);
console.log(st);
if (numberofscroll < 2) {
change_background2(numberofscroll);
} else if (numberofscroll < 3) {
change_background3(numberofscroll);
} else if (numberofscroll < 4) {
change_background4(numberofscroll);
}
lastScrollTop = st;
});
function change_background2(numberofscroll) {
if (numberofscroll == 2) {
$("#home").css("background-position","0 -652px");
}
}
function change_background3(numberofscroll) {
if (numberofscroll == 3) {
$("#home").css("background-position","0 -1326px");
}
}
function change_background4(numberofscroll) {
if (numberofscroll == 4) {
$("#home").css("background-position","0 -1978px");
}
}
});

I think you want to use the innerWidth property of window. (https://developer.mozilla.org/en/docs/Web/API/window/innerWidth).

Related

I had a problem with looping a function in javascript

My code snippet's purpose is to reveal an animation while the scrollY is on 0 if the scrollY is above 0 it will reveal other animations, however, the code only works once.
function reveal() {
var reveals = document.querySelectorAll(".navbar");
var i = 0;
for ( i; i < reveals.length; i++) {
if (window.scrollY > 0) {
reveals[i].classList.add("active");
} else if (window.scrollY == 0) {
reveals[i].classList.add("nactive");
} else {
}
}
}
window.addEventListener("scroll", reveal);
reveal();
the function needs to be looped but I don't know how.

How do I make auto fontSize in Javascript?

I was trying to use the same function of fontSize() in mobile view to make it responsive but I don't know to do it. This is what I'm using in window view
document.getElementById('hakdog').onload = function () {func()};
function func() {
var str = document.getElementById("voter").innerHTML;
var a = str.length;
if(a >= 40) {
voter.style.fontSize = "18px";
} else if(a >=30) {
voter.style.fontSize = "22px";
} else {
voter.style.fontSize = "27px";
}
}
Is there any same function for mobile view? I only know some function but I know its not responsive
$(document).ready(function(){
if($(window).width() < 480) {
$('h1').css('font-size','10px');
$('h2').css('font-size','8px');
$('h3').css('font-size','6px');
$('h4').css('font-size','4px');
}
});
EDIT
I was trying to make it responsive using java just like on the first code I given, normal .css is not gonna work since its only going to give for h1, h2, h3, etc. I was pointing out that I wanted to make the responsive if the full name reached 40 letters then the fontSize would be 18px same with other functions given
EDIT 5:30pm MARCH 29
This is what I tried so far but didn't work as what I expected.
document.getElementById('hakdog').onload = function () {func()};
function func() {
$(document).ready(function() {
function resizes() {
if($(window).width() < 480) {
var str = document.getElementById("voter").innerHTML;
var a = str.length;
if(a >= 40) {
voter.style.fontSize = "9px";
} else if(a >=30) {
voter.style.fontSize = "10px";
} else {
voter.style.fontSize = "15px";
}
}
}
resizes();
$(window).resize(resizes);
})
}
Edit: Made changes to include the font size based on the length of the content.
This should work. You can check this out on the full page in the below code snippet.
$(document).ready(function() {
function resizeMe() {
if ($(window).width() < 480) {
if ($("#name").text().length < 5) {
$('h1').css('font-size', '46px');
} else {
$('h1').css('font-size', '10px');
}
$('h2').css('font-size', '8px');
$('h3').css('font-size', '6px');
$('h4').css('font-size', '4px');
} else {
$('h1').css('font-size', '20px');
$('h2').css('font-size', '18px');
$('h3').css('font-size', '16px');
$('h4').css('font-size', '14px');
}
}
resizeMe();
$(window).resize(resizeMe);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="name">Helo</h1>
<h2>Yes</h2>
<h3>Nooooooooooooooooooooooooooo</h3>
<h4>okkkkkk</h4>
Do you try to change 'px' to 'rem', 'rem' resize in relation to the size of the screen.
This is what i meant for auto sizing for every device
var wid = $(window).width();
if(wid < 320) {
var str = document.getElementById("voter").innerHTML
var a = str.length;
if(a >= 40) {
voter.style.fontSize = "9px";
} else if(a >= 25) {
voter.style.fontSize = "11px";
} else {
voter.style.fontSize = "15px";
}
}
Thanks for everyone commented out!

clear javascript : determine which link was clicked

I have a cycle of links and I determined click event on them. And I want to define if navbar[1].clicked == true {doing something} else if navbar[2].cliked == true {doing something} etc. "By if else in " reveal functional callbackFn".
Here is the code:
var navbar = document.getElementById("navbar").getElementsByTagName("a");
for (var i = 0; i < navbar.length; i++) {
navbar[i].addEventListener('click', function() { reveal('top'); });
}
function reveal(direction) {
callbackFn = function() {
// this is the part where is running the turning of pages
classie.remove(pages[currentPage], 'page--current');
if (navbar[1].clicked == true) {
currentPage = 0;
} else if(navbar[1].clicked == true) {
currentPage = 1;
} else if(navbar[2].clicked == true) {
currentPage = 2;
} else if(navbar[3].clicked == true) {
currentPage = 3;
} else if(navbar[4].clicked == true) {
currentPage = 4;
};
classie.add(pages[currentPage], 'page--current');
};
}
This is typically a problem of closure.
You can make the following change
Here the call back function of the addEventListener is an IIFE, & in the reveal function pass the value of i
var navbar = document.getElementById("navbar").getElementsByTagName("a");
for (var i = 0; i < navbar.length; i++) {
navbar[i].addEventListener('click', (function(x) {
reveal('top',x);
}(i))};
}
In this function you will have access to
function reveal(direction,index) {
// not sure what this function is mean by, but you will have the value of `i` which is denote the clicked element
callbackFn = function() {
// this is the part where is running the turning of pages
classie.remove(pages[currentPage], 'page--current');
if (index == 1) {
currentPage = 0;
} else if (index == 1) {
currentPage = 1;
} else if (index == 2) {
currentPage = 2;
} else if (index == 3) {
currentPage = 3;
} else if (index == 4) {
currentPage = 4;
};
classie.add(pages[currentPage], 'page--current');
};
}
Here is the solution in my case.
Thank you brk for helping in any case, thanks again.
// determine clicked item
var n;
$('#navbar a').click(function(){
if($(this).attr('id') == 'a') {
n = 0;
} else if($(this).attr('id') == 'b') {
n = 1;
} else if($(this).attr('id') == 'c') {
n = 2;
} else if($(this).attr('id') == 'd') {
n = 3;
} else if($(this).attr('id') == 'e') {
n = 4;
};
});
var pages = [].slice.call(document.querySelectorAll('.pages > .page')),
currentPage = 0,
revealerOpts = {
// the layers are the elements that move from the sides
nmbLayers : 3,
// bg color of each layer
bgcolor : ['#52b7b9', '#ffffff', '#53b7eb'],
// effect classname
effect : 'anim--effect-3'
};
revealer = new Revealer(revealerOpts);
// clicking the page nav
document.querySelector("#a").addEventListener('click', function() { reveal('cornertopleft'); });
document.querySelector("#b").addEventListener('click', function() { reveal('bottom'); });
document.querySelector("#c").addEventListener('click', function() { reveal('left'); });
document.querySelector("#d").addEventListener('click', function() { reveal('right'); });
document.querySelector("#e").addEventListener('click', function() { reveal('top'); });
// moving clicked item's `n` into the function
function reveal(direction) {
var callbackTime = 750;
callbackFn = function() {
classie.remove(pages[currentPage], 'page--current');
currentPage = n;
classie.add(pages[currentPage], 'page--current');
};
revealer.reveal(direction, callbackTime, callbackFn);
}

How can I write this code more elegantly?

I'm writing the same code three times for the different pages of my WordPress site. I feel that it could be written more elegantly but unfortunately I'm not at the skill level yet to achieve this. Is there any way to combine all of this into something more concise? It would also probably help me learn more about what can and can't be done with JavaScript.
if (jQuery(document.body).hasClass("home")) {
jQuery(window).scroll(function () {
var threshold = 654;
if (jQuery(window).scrollTop() >= 654)
jQuery('#sidebar').addClass('fixed');
else
jQuery('#sidebar').removeClass('fixed');
});
} else if (jQuery(document.body).hasClass("single") || jQuery(document.body).hasClass("page")) {
jQuery(window).scroll(function () {
var threshold = 20;
if (jQuery(window).scrollTop() >= 20)
jQuery('#sidebar').addClass('fixed');
else
jQuery('#sidebar').removeClass('fixed');
});
} else {
jQuery(window).scroll(function () {
var threshold = 236;
if (jQuery(window).scrollTop() >= 236)
jQuery('#sidebar').addClass('fixed');
else
jQuery('#sidebar').removeClass('fixed');
});
}
var threshold = 236;
if (jQuery(document.body).hasClass("home")) {
threshold = 654;
} else if (jQuery(document.body).hasClass("single") || jQuery(document.body).hasClass("page")) {
threshold = 20;
}
var scrolled = false;
jQuery(window).scroll(function () {
if (!scrolled && jQuery(window).scrollTop() >= threshold){
jQuery('#sidebar').addClass('fixed');
scrolled = true;
} else if (scrolled && jQuery(window).scrollTop() < threshold) {
jQuery('#sidebar').removeClass('fixed');
scrolled = false;
}
});
UPDATE: I was created a simple demo to show how to implement sidebar scrolls within his parent.
Demo on CodePen
Damn.. I got beat. Well, I'm still posting this anyway.
var scrollTopFn = function(amount){
$(window).scroll(function(){
// this is a ternary statement, basically a shorthand for writing if else statements
$(window).scrollTop() >= amount
? $('#sidebar').addClass('fixed')
: $('#sidebar').removeClass('fixed');
});
}
if ($(document.body).hasClass('home')) {
scrollTopFn(654);
} else if ($(document.body).hasClass('single')){
scrollTopFn(20);
} else {
scrollTopFn(236);
}
Could be:
var threshold = 236;
switch (jQuery(document.body).attr("class")) {
case "home":
threshold = 654
break;
case "single":
case "page":
threshold = 20
break;
}
$(window).scroll(function () {
if (jQuery(window).scrollTop() >= threshold )
jQuery('#sidebar').addClass('fixed');
else
jQuery('#sidebar').removeClass('fixed');
});
Your code could be simplified to:
var $body = jQuery(document.body),
threshold = $body.hasClass("home") ? 654
: $body.hasClass("single") || $body.hasClass("page") ? 20
: 236;
jQuery(window).on('scroll', function() {
jQuery('#sidebar').toggleClass('fixed', state);
});
But this one should have better performance:
var $body = jQuery(document.body),
state = false,
threshold = $body.hasClass("home") ? 654
: $body.hasClass("single") || $body.hasClass("page") ? 20
: 236;
jQuery(window).on('scroll', function() {
if(state != (state = jQuery(window).scrollTop() >= threshold))
jQuery('#sidebar').toggleClass('fixed', state);
});

Execute & Stop JavaScript when page reach a certain position

I have a script that I want to execute only when a user reaches a position X (under my Nav bar) and to stop only when the user reaches this position X again (under my Nav bar).
How to achieve this effect?
EDIT:
How can I implement this code:
var reachedFromTop = false;
var reachedFromBottom = false;
$(window).scroll(function() {
//After scrolling 100px from the top...
if ($(window).scrollTop() > 100 ) {
if (!reachedFromTop) something();
reachedFromTop = true;
} else if (reachedFromTop && otherCondition) {
if (!reachedFromBottom) somethingElse();
reachedFromBottom = true;
}
});
in my existing script:
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('.main-navigation').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
if(Math.abs(lastScrollTop - st) <= delta)
return;
if (st > lastScrollTop && st > navbarHeight){
$('.main-navigation').removeClass('nav-down').addClass('nav-up');
} else {
if(st + $(window).height() < $(document).height()) {
$('.main-navigation').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}
you should be able to do something like this.
var reachedFromTop = false;
var reachedFromBottom = false;
$(window).scroll(function() {
//After scrolling 100px from the top...
if ($(window).scrollTop() > 100 ) {
if (!reachedFromTop) something();
reachedFromTop = true;
} else if (reachedFromTop && otherCondition) {
if (!reachedFromBottom) somethingElse();
reachedFromBottom = true;
}
});
and you need to include jquery as your dependency

Categories

Resources