How to write responsive text for different screen sizes - javascript

If I want to make responsive text I would probably write something like that:
$(window).resize(function ()
{
if $(document).width() <= 320) {
$('#mydiv').html('something')
}
if $((document).width() > 320) && (document).width() <= 480)) {
$('#mydiv').html('something longer')
}
if $((document).width() > 480) && (document).width() <= 768)) {
}
//and so on
}
I don't think it is most efficient (and messy code) - I think that there must be a way to make it easier - Let's assume that I can write this object which stores all the data:
var divTextPerScreenWidthMap = {
{'360','click'},
{'480','click it'},
{'768','click it right'},
{'1024','you know you want to click it'},
{'1280','click this button which is very long will help you'}
}
After I have done so, is there a simple function I can write that takes this data and simplify my many-conditions function? some sort of way to tell javascript how to build me the specific function I need?
something like this thing but in real code:
for (objects in divTextPerScreenWidthMap) {
create If Statement for Nth Object(object)
}
thanks,
Alon

I think using a lookup table like that is a bit overkill. Note that your code becomes much simpler if you use else ifs properly.
if $(document).width() <= 320) {
$('#mydiv').html('something')
} else if ($(document).width() <= 480) {
$('#mydiv').html('something longer')
} else if ($(document).width() <= 768) {
...
}

Something like this should work - it'll set it once for the first screen width (360) then for each subsequent one, if the width is smaller than the document's width, it'll overwrite it.
var docWidth = $(document).width();
for (var i in divTextPerScreenWidthMap)
{
if (parseInt(divTextPerScreenWidthMap[i][0]) < docWidth || i == 0)
{
// Set something here
console.log( divTextPerScreenWidthMap[i][1] );
}
}

Related

Replace url (window.location) when div height gets bigger than 50px

Newbie here. I'm trying to change the website's page/url using window.location.replace when div #valor height gets bigger than 50px.
Details:
This div #valor increases its height on each click. But when it achieves at least 50px, I need to redirect the user to another page.
I've tried a lot of different approaches but I know that there's something missing on each one. I'll list them below for reference. I do think that the problem is with the way I structure my code...
var maskHeight = $("#valor").css('height');
if (maskHeight > 50){
window.location.replace("https://google.com");
}
else {
alert("if I'm here it means it didn't work"); //just testing
}
});
And I have a lot of different options that didn't work but they all have this if statement:
if ($('#valor').height() > 40) {
window.location.replace("https://google.com");
}
I've also tried something like this:
var div = $("#valor").height();
var win = 50;
if (div > win ) {
window.location.replace("https://google.com");
}
My first approach, not listed here, didn't work because it compared the value right on the first click. And I just want to make something like: when #valor height gets bigger than/achieves 50px > change url.
Thank you in advance! Any help is very much appreciated.
you compare a string with (for example) 10px with an integer:
var maskHeight = $("#valor").css('height'); // output for example 10px
if (maskHeight > 40){ . //than you compare it if(40px > 40)
window.location.replace("https://google.com");
}
change your var to:
var maskHeight = $("#valor").height();
ok you edited your post:
can you show us your click handler function?
I think this is the right way you have do do it:
var maskHeight = $("#valor").height();
$("#valor").on('click', function()
maskHeight = maskHeight + 10;
if (maskHeight > 40){
window.location.replace("https://google.com");
}
else
{
alert("if I'm here it means it didn't work"); //just testing
}
});

Add class to element if y-position bigger as another element

I want to add a class to an element as soon as the users' scroll-position has "hit" a special - other - element.
I try to use that code therefore
var hands = $(".sw_3--breit");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
// The next line is the one I am asking for help
if (scroll >= window.innerHeight)
{
hands.addClass("fixed");
} else {
hands.removeClass("fixed");
}
});
Which works nice by adding the class after the scroll is bigger then the users display-height I guess. But I want to add - and afterwards also remove - a class when then user has "hit" another element.
What I am asking for is something - very roughly and stupid I know - like:
var other_elements_position = $(".other_element"().position;
if (scroll >= other_elements_position)
How can I achieve that? And I already do use jquery for other things, so using jquery there would make sense I guess.
Thanks!
For people that got the same problem as I do have, this worked for me:
var hands = $(".sw_3--breit");
var hands_original = $(".sw_8").position();
var hands_off = $("#target_agentur").position();
var hands_corrected = (hands_original.top + 680) // here I add a small delay to the trigger of the "animation"
$(window).scroll(function () {
var scroll = $(window).scrollTop();
if (scroll >= hands_corrected && scroll <= hands_off.top) // I doublecheck against 2 heights
{
hands.addClass("fixed");
} else {
hands.removeClass("fixed");
}
});

Run function() if appear in viewport ? jquery-viewport-checker

I use anime-js for create an animation. But, It is far in the page. I would like to launch my animation function when the section in which the item to be animated appears on the screen.
I tried a plugin that I like to use (jquery viewportchecker) but it does not seem to do that.
Can you help me ?
Thank you
I found a solution. The problem with your method is that the function repeats itself to infinity.
I create a little function for check if element is visible. With that, no plugin needed.
function checkVisible( elm, evale ) {
var evale;
evale = evale || "object visible";
var viewportHeight = $(window).height(), // Viewport Height
scrolltop = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (evale == "object visible") return ((y < (viewportHeight + scrolltop)) && (y > (scrolltop - elementHeight)));
if (evale == "above") return ((y < (viewportHeight + scrolltop)));
}
I also created a variable var counter = 0;. And as soon as the function is called, I increment by 1.
$(window).on('scroll',function() {
if (counter == 0){
if (checkVisible($('.frontend'))) {
// Your function here
}
}
}
At the first time the function will be called, counter will be 1, and thus, the function will not repeat. Thank you for your help !
jQuery.appear
This plugin implements custom appear/disappear events which are fired when an element became visible/invisible in the browser viewport.
https://github.com/morr/jquery.appear
$('someselector').on('appear', function(event, $all_appeared_elements) {
// this element is now inside browser viewport
});
$('someselector').on('disappear', function(event, $all_disappeared_elements) {
// this element is now outside browser viewport
});
Also this plugin provides custom jQuery filter for manual checking element appearance.
$('someselector').is(':appeared')
Have you tried using JQuery's on load method?
Something like
$(document).on('load', '.exampleClass', function() { //do stuff } )

Variable two options

Had a look around and couldn't find anything that solved this very simple problem.
I'm still learning jQuery so prior apologies for my stupidity on this one, I know it's a very simple fix but things like using || and trying to using if and else inside a var don't see to work for me.
Essentially this is what I have currently. All I want is to add/remove the class "whitebg" depending on the scroll position and height of the element, which works well.
The problem is trying to query two different elements that each need a different height buffer as you can see (-167 and -90) so cannot be grouped, but need to be 'either / or' so both are accounted for.
Many thanks
Rb
jQuery(window).scroll(function() {
Menuresize();
});
function Menuresize() {
var myheight = jQuery(".section-image-slider, .section-video-slider").height() - 90;
var myheightalt = jQuery(".area-tag").height() - 167;
var scroll = jQuery(window).scrollTop();
if (scroll > myheight) {
jQuery(".bt-menu").addClass("whitebg");
}
elseif (scroll > myheightalt){
jQuery(".bt-menu").addClass("whitebg");
}
else {jQuery(".bt-menu").removeClass("whitebg");}
};
jQuery(window).resize(function() {
Menuresize();
});
If I understand your problem correctly, toggleClass can take a boolean parameter to toggle on/off the class specified. You can then work out a compound boolean expression that results in true or false:
e.g.
jQuery(".bt-menu").toggleClass("whitebg", scroll > myheight || scroll > myheightAlt);
I found the question a little hard to follow so, if it is something else you wanted, please clarify :)
Have your Menuresize function take parameters for the selectors and height, and then just call it for each:
function Menuresize(selector, height) {
var myheight = jQuery(selector).height() - height;
var scroll = jQuery(window).scrollTop();
if (scroll > myheight) {
jQuery(".bt-menu").addClass("whitebg");
}
else {
jQuery(".bt-menu").removeClass("whitebg");
}
};
jQuery(window).resize(function() {
Menuresize(".section-image-slider, .section-video-slider", 90);
Menuresize(".area-tag", 167);
});

Stop/start window resize when viewport width reaches some value

The goal
If user's viewport reaches some value, I need to stop or start:
jQuery(window).on('resize'){ // ... }
The scenario
Let's suppose that we have the following array (in JavaScript):
var ranges = [1024, 1280];
I'm using jQuery(window).on('resize'){} with some ifs inside to do things when user's viewport raches a width between the values set by ranges' array.
But I just want to run those "things" when the viewport is out or in range with the widths from the array. I mean, jQuery(window).on('resize'){} should stop to run when the user's viewport is between 1024px x 1280pxof width, but its need to wake up when the viewport is out of range to do another thing that I want.
Playground
To have a better comprehension of the problem, open your console and take a look in this jsFiddle.
You'll see that the console prints
"Hi" for each time that jsFiddle JavaScript's Window has its width changed, and I want to display it once.
Oh my god, are you stupid?! Your script is wrong because nothing is printing here. Calm down, fella! jsFiddle doesn't interpret $(window) as your browser's window. To run the function, you should to resize result window. Look:
What I'm expecting, actually
Based on the above's script, I want to see Hi! just when the viewport enters in some width between 1024px x 1280px — once. When the viewport is outside, nothing happens, but when viewport enters in the specified width again, prints Hi! — again and once.
What have I tried?
Actually, I'm stuck. My mind can't think in the solution — I need a light!
Doubts? I haven't made clear enough?
Comment your question, please!
Duplicated?
Post the link or marks as duplicate — I didn't saw any similar topic like this before (sorry for this).
You just need to keep track of the state. Here's a Fiddle that I think does what you want:
var isInRange = (function() {
var test = function() {
return $(window).width() >= 1024 && $(window).width() <= 1280;
};
var current = test();
return function() {
if (test()) {
if (!current) {
current = true;
console.log('Hi!');
}
} else {
current = false;
}
}
}())
$(window).on('resize', isInRange);
Update
Okay, after all these comments, I'm really not happy with the code as written. Here's another version of the same ideas, cleaning up some of the code and adding the onExit functionality too:
var isInRange = (function() {
var $window = $(window);
var test = function() {
var ww = $window.width();
return ww >= 1024 && ww <= 1280;
};
var inRange = test();
var onEnter = function() {
console.log("Hi");
};
var onExit = function() {
console.log("Bye");
};
return function() {
test() ? (!inRange && (inRange = true) && onEnter())
: ((inRange && onExit()) || (inRange = false));
};
}())
$(window).on('resize', isInRange);
It's a little more clean, a little more organized, and slightly more efficient. But nothing really substantive has changed.
You'll need to use a flag to keep track of the state, I've updated your JSFiddle as follows:
var inRange;
function isInRange() {
if ($(window).width() >= 1024 && $(window).width() <= 1280){
if (!inRange){
inRange = true;
console.log('Hi!');
}
} else {
inRange = false;
}
}
$(window).on('resize', isInRange).trigger('resize');
EDIT
To show a different message only once depending on whether the window is inside or outside the set range, simply keep track of two states with flags like so:
var inRange, outsideRange;
function isInRange() {
if ($(window).width() >= 1024 && $(window).width() <= 1280){
outsideRange = false;
if (!inRange){
inRange = true;
console.log('Hi!');
}
} else {
inRange = false;
if (!outsideRange){
outsideRange = true;
console.log('Bye!');
}
}
}
$(window).on('resize', isInRange).trigger('resize');
Here is the updated JSFIddle.
I hope this helps!
just tell it when to go
var min=1024, max=1280, go;//values
$(window).on('resize', function() {//on resize
var ww = $(window).width();//get window width
if (go && ww >= min && ww <= max) {//go & in range
console.log('Hi!');//print 'Hi!'
go = false;//!go
} else if (!go && (ww<min || ww>max)) {//!go & out of range
console.log('Bye!');//print 'Bye!'
go = true;//go
}
});
made a fiddle: http://jsfiddle.net/filever10/zP39t/

Categories