I need some javascript condition like media query - javascript

I want to add some condition in jquery like media queries in CSS, anyone can help me with this? I try the code below but is not working:
jQuery(document).ready(function(){
if (jQuery(window).width() >= 320) && (jQuery(window).width() <= 479) {
}
if (jQuery(window).width() >= 480) && (jQuery(window).width() <= 567) {
}
});

You have parentheses around your individual conditions, but not around the if conditions as a whole.
Try this:
jQuery(document).ready(function(){
alert("Running");
alert(jQuery(window).width());
if ((jQuery(window).width() >= 320) && (jQuery(window).width() <= 479)) {
alert('Small screen');
} else
if ((jQuery(window).width() >= 480) && (jQuery(window).width() <= 567)) {
alert('Large screen');
} else {
alert("Biggest screen");
}
});
Note the extra parentheses after if and before {

You actually don't need mediaqueries in JS to do your task the right way. First of all: how to work with media queries in JS. You can use matchMedia. Here is a brief documentation.
Here is a simple example:
var smallMatcher = matchMedia('(max-width: 480px)');
var biggerMatcher = matchMedia('(max-width: 1024px)');
var run = function(){
if(smallMatcher.matches) {
//run code for small
} else if(biggerMatcher.matches){
//run code for bigger
} else {
//run code for else
}
};
//now run it
run();
//in case you need to dynamically change on resize
//use addListener
smallMatcher.addListener(run);
biggerMatcher.addListener(run);
But as said, you don't need this. What you actually need to do is simple separation of concerns. Don't mix your behavior with your CSS. Simply add focus/blur or focusin/focusout events, the add or remove a class and do everything else in CSS.
This should result in clean and simple code, here is an example:
$('#searchbox')
.on('focus', function(){
$(this).closest('form').addClass('focused-field');
})
.on('blur', function(){
$(this).closest('form').removeClass('focused-field');
})
;
Everything else can and should be handled in CSS.
And In case you need the modify the style for the input button also if the button itself is focused and not only the search input you can see the following fiddle.

Related

Combine Window Resize with Text Length

I need some help writing a function with multiple if statements (unless there is a better method). I basically want to truncate text length based on window size. So if the viewport is less than 400px and the text length is greater than 35, then truncate using this method below...
$('option').each(function () {
var text = $(this).text();
if (text.length > 35) {
text = text.substring(0, 35) + '...';
$(this).text(text);
}
});
The function for window resize (basically combine above with below):
$(document).ready(function(){
if($( window ).width() < 400){
//do something;
}else{
//do something else;
}
});
$( window ).resize(function() {
if($( window ).width() < 400){
//do something;
}else{
//do something else;
}
});
Did a little more research and got it working with this code:
$(document).ready(myfunction);
$(window).on('resize',myfunction);
$('option').each(myfunction);
function myfunction() {
var text = $(this).text();
if (text.length > 35 == ($(window)).width() < 400) {
text = text.substring(0, 35) + '...';
$(this).text(text);
}
}
I wonder if/how a math function could calculate viewport width as a range and change truncation up to a maximum breakpoint?
I ended up answering my own question. So, I am posting it here incase someone else has a similar need or can improve what I have done...
Basically, I am truncating select option boxes by applying character length and window width. This prevents very lengthy option text to flow past its container and beyond the screen. I am sure there is a more efficient way to code this, but my tests appear to be successful which works for now.
/**
* Truncate lengthy option text in select boxes
*/
var defaultString=$('option').text();
function checkWidth() {
if($(window).width() > 600){
$('option').each(function(i){
len=$(this).text().length;
if(len>65)
{
$(this).text($(this).text().substr(0,65)+'...');
}
});
return false;
}
if ($(window).width() > 451 && $(window).width() < 599 ) {
$('option').each(function(i){
len=$(this).text().length;
if(len>50)
{
$(this).text($(this).text().substr(0,50)+'...');
}
});
return false;
}
if($(window).width() < 450){
$('option').each(function(i){
len=$(this).text().length;
if(len>35)
{
$(this).text($(this).text().substr(0,35)+'...');
}
});
return false;
}
}
checkWidth();
$(window).resize(checkWidth);
$(document).ready(checkWidth);
The last three lines bind 'checkWidth' and window 'resize' (which can also be 'width' or 'height') depending upon what you are achieving. Binding must be done before you can execute the function events.

click function only available above 1024px breakpoint

I have a mute button that I only want to work above screen width 1024.
The function should not be available below the mentioned break point. I have tried a couple of ways but still not able to achieve this. Any pointers would be helpful. Please see my snippet below:
if($(window).width() > 1024) {
$("#mute").click(function() {
if ($("video").prop('muted')) {
$("video").prop('muted', false);
$(this).removeClass("fa-volume-off");
$(this).addClass("fa-volume-up");
} else {
$("video").prop('muted', true);
$(this).removeClass("fa-volume-up");
$(this).addClass("fa-volume-off");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Removed javascript error, It should work now.
if($(window).width() > 1024) {
$("#mute").click(function() {
if ($("video").prop('muted')) {
$("video").prop('muted', false);
$(this).removeClass("fa-volume-off");
$(this).addClass("fa-volume-up");
} else {
$("video").prop('muted', true);
$(this).removeClass("fa-volume-up");
$(this).addClass("fa-volume-off");
}
});
}
I think, You should check for the window width if there was a resize and then perform the necessary action.
Something like this:
$(document).ready(function(){
$( window ).resize(function() {
if(window.width < 1024)
{
$("#mute").off("click");
}
else
{
$("#mute").click(function() {
. . .
})
}
});
$("window").trigger("resize"); // On trigger resize to make button active if window is already > 1024
})
You're adding click handler when executing the code, not when doing the click. when width > 1024px at the time you execute that code the handler gets created and will still work when width drops below 1024px. Similarly when execute that code and width < 1024px then the click handler will never be created!
So, try this code (inside $.ready or similar):
$("#mute").click(function() {
if ($(window).width() <= 1024) return; // maybe return false;
if ($("video").prop('muted')) {
$("video").prop('muted', false);
$(this).removeClass("fa-volume-off");
$(this).addClass("fa-volume-up");
} else {
$("video").prop('muted', true);
$(this).removeClass("fa-volume-up");
$(this).addClass("fa-volume-off");
}
});
EDIT: as already commented above while I was answering...
Just try to swap the if statement with the click event handler.
$(document).ready(function() {
$("#mute").click(function() {
if ($(window).width() > 1024) {
alert("Clicked");
}
});
});
Here's a Fiddle for you to test.

JavaScript media queries breaking greensock

I am trying to create a Navigation Bar that slides in and out when clicked on using JavaScript and Greensock. For some reason, the on click action is randomly not working when clicked on at different sizes but sometimes it works perfectly fine.
My code is below, you can find a live example of this navigation at: http://www.kramergraphicdesign.com/Maura_Website/
var resize = function(){
var viewportWidth = $(window).width();
var lastLiWith = $('#logo').width();
console.log(openOrShut + " this is the true false var");
if ($(window).width() >= 0 && $(window).width() <= 639 ) {
console.log("mobile");
$("#logo, #close, .arrow-right").click(function()
{
console.log("mobile-click");
if(openOrShut === false)
{
TweenLite.to("#custom-nav",".5",{x:viewportWidth-lastLiWith});
openOrShut = true;
}
else{
TweenLite.to("#custom-nav",".5",{x:0});
openOrShut = false;
}
});
}
else if ($(window).width() >= 640 ) {
console.log("tablet");
$("#logo, #close, .arrow-right").click(function()
{
console.log("tablet-click");
if(openOrShut === false)
{
TweenLite.to("#custom-nav",".5",{x:400});
openOrShut = true;
}
else{
TweenLite.to("#custom-nav",".5",{x:0});
openOrShut = false;
}
});
}
else if ($(window).width() >= 1025 && $(window).width() <= 10000 ) {
console.log("dekstop");
$("#logo, #close, .arrow-right").click(function()
{
console.log("desktop-click");
if(openOrShut === false)
{
TweenLite.to("#custom-nav",".5",{x:400});
openOrShut = true;
}
else{
TweenLite.to("#custom-nav",".5",{x:0});
openOrShut = false;
}
});
}
};
$(document).ready(resize);
$(window).resize(function(){
resize();
});
First of all, the resize event can occur an awful lot, especially during a drag to resize the window. This means two things:
Minimise the amount of work you do so it runs fast, or debounce the function (e.g. using Lodash) so it only runs after you stop receiving resize events for a short time.
More importantly, you are adding a new click handler every single time.
So the reason it "randomly" doesn't do anything is that whenever you click, you actually run your function to toggle the menu many, many times if you have previously resized the window at all. If that number of times happens to be even, then there is no net effect.
There are probably a number of ways to fix this, but here are two:
Attach a click handler once, but check the width inside the handler to determine how far to animate it to / how to respond differently to different sizes.
Unregister existing click events first (using jQuery's .off()) before re-adding them, so there is only ever the one handler registered. I recommend using an event namespace so you can deregister everything on the namespace at once.
Bonus observation: your condition for the tablet widths means the desktop code will never run, because there is no <= 1024 condition for the tablet block.

Animate some divs only once

I am trying to animate some divs after the user scrolls to a specific position on the page. the problem is that i want it to happen only once. I used Boolean flags but it doesn't seem to like it.
What are u all suggest me to do?
::the code Its not even running
FYI I don't want to use PHP
var once = false;
$(document).ready(function() {
if ($(window).scrollTop() > 760 && once == false) {
$('.hash').each(function(i) {
$(this).fadeOut(0).delay(1000 * i).fadeIn(1000);
});
once = true;
}
)};
Thanks!
From your question
after the user scrolls to a specific position on the page
Listen to scroll event
$(document).ready(function() {
var once = false;
$(document).on('scroll', function(){
if ($(window).scrollTop() > 760 && once==false){
$('.hash').each(function(i) {
$(this).fadeOut(0).delay(1000*i).fadeIn(1000);
});
once=true;
}
});
)};
Alternative from comments. Check if element has a class (or attribute) or not. Below code checks if the element has the data-noanimate attribute. If yes it will not animate, if not it will animate and add data-noanimate so that it will animate once.
$(document).ready(function() {
$(document).on('scroll', function(){
if ($(window).scrollTop() > 760){
$('.hash').each(function(i) {
if($(this).attr('data-noanimate') === undefined){
$(this).attr('data-noanimate','true').fadeOut(0).delay(1000*i).fadeIn(1000);
}
});
}
});
)};
var once=false;
$(document).ready(function() {
if ($(window).scrollTop() > 760 &&once==false)
{
$('.hash').each(function(i) {
$(this).fadeOut(0).delay(1000*i).fadeIn(1000);});
once=true;
}
});
Your brackets on the end of the ready function were flipped.
The other answer is correct, but it can be better like this:
$(function() {
$(window).on('scroll', function(){
if ($(window).scrollTop() > 760) {
$('.hash').each(function(i) {
$(this).fadeOut(0).delay(1000 * i).fadeIn(1000);
});
// without boolean value,you can off `scroll` event
$(window).off('scroll');
}
})
});

Using scroll and resize handlers together

Can I use resize and scroll handlers together like this:
$(window).on('scroll resize',function(){
if($(window).width() == "1024"){
if($(window).scrollTop() == 400){
$('div.foo').addClass('red') ; //to change to red color
}
}
}) ;
The way I used , is it the correct way, what are the implications of this ? Is there a better way to incorporate both the handlers ? Thanks for your reply. Please let me know if you need a simulation of the above code. Thank you !
do this
var handler = function(){
if ($(window).width() == "1024") {
if ($(window).scrollTop() == 400) {
$('div.foo').addClass('red') ; //to change to red color
}
}
};
$(window).on('scroll',handler).on('resize',handler);

Categories

Resources