Run function on window resize below specific window size - javascript

I have a function that breaks an address down, line by line based on comma separation. I need to only run this when the window is below 750px and return the text to one line above 750px. I have the following function which breaks the text down:
var fixed = $('.location-header > p').text();
var address = fixed.substring(0, fixed.lastIndexOf(',')).replace(/,/g, "<br />") + fixed.substring(fixed.lastIndexOf(','));
$('.location-header > p').html(address);
I'm trying to use .resize() function in jquery, but it doesn't seem to be triggering properly.
When function runs properly, text should look like this:
123 Nowhere Ln
Suite 200
Somewhere, NY 10009
JSFIDDLE: LINK

With Javascript: On resize, you can check the window width with $(window).width() and break/unbreak the address accordingly.
JSFiddle: https://jsfiddle.net/mu1zpvoq/
JSFiddle (ES6 + 1 line functions): https://jsfiddle.net/mu1zpvoq/4/
var fixed = $('.location-header > p')[0].innerHTML.replace('/(,)(?=\s{1}\D{2}[^\s][^\d{5,}])/g', "<br />");
var address = fixed.substring(0, fixed.lastIndexOf(',')).replace(/,/g, "<br />");
function breakAddress () {
$('.location-header > p').html(address)
}
function fixAddress () {
$('.location-header > p').html(fixed)
}
function toggleAddress () {
if ($(window).width() < 750) {
breakAddress()
} else {
fixAddress()
}
}
$(window).on('resize', toggleAddress)
$(document).ready(toggleAddress)
HOWEVER you can definitely just do this with CSS:
HTML:
<p class="address">
<span>123 Nowhere Ln</span>
<span>Suite 200</span>
<span>Somewhere</span>
</p>
CSS:
.address > span
display: block
#media all and (min-width: 750px)
.address > span
display: inline
.address > span:after
content: ', '

It would be better to use CSS media queries (reference) instead of resize callbacks.
You could split the address into separate html elements during the page loaded callback and then change display styles regarding to window's width with media queries.

Related

How to incorporate JS media Queries and Scroll listening?

I'm currently making an element visible when my nav is at the top of the page. I'd like the element to be hidden if the page gets to max-width: 900px;. I've tried using modernizer for JS media queries but I ca't seem to get it to work.
Code:
var a = $(".menu").offset().top;
function scrollListener(){
if($(document).scrollTop() > a)
{$('.hidden-logo').css({"opacity": "1","display": "block"});
$('.menu').css({"margin-left": "-130px"})
} else {
$('.hidden-logo').css({"opacity": "0","display": "none"});
$('.menu').css({"margin-left": "0px"})
}
};
$(document).scroll(scrollListener);
You were checking the scroll position the wrong way - I think you want the logo to disappear when the current scroll is greater than the top of the logo, not less.
I added a msgS div (for demo purposes only) that will show you the current scroll value against the top-of-menu static value. I also added a 100px fudge factor to the menu location to make it more clear in the demo when the current scroll reaches that position. I use these temporary msg divs myself when working out my code, and then remove them when I've got it all sorted and ready for production.
And this is all you need to check the media query in javascript:
var winmed = window.matchMedia("(max-width: 700px)");
if (winmed.matches){ //do something }
And that can go into a listener function exactly like your scroll listener.
var gloShowLogo = true;
var a = $(".menu").offset().top;
var fudge = 100; //100px fudge factor so can SEE div disappear
function scrollListener(){
updateScrollMsg();
var currScroll = $(document).scrollTop();
var topOfMenu = a+fudge;
if( gloShowLogo && currScroll < topOfMenu ){
$('.hidden-logo').css({"opacity": "1","display": "block"});
$('.menu').css({"margin-left": "-130px"})
} else {
$('.hidden-logo').css({"opacity": "0","display": "none"});
$('.menu').css({"margin-left": "0px"})
}
};
function resizeListener(){
updateMediaMsg();
var winmed = window.matchMedia("(max-width: 500px)");
if (winmed.matches){
$('.hidden-logo').css({"opacity": "1","display": "block"});
gloShowLogo = true;
} else {
$('.hidden-logo').css({"opacity": "0","display": "none"});
gloShowLogo = false;
}
}
$(window).scroll(scrollListener);
$(window).resize(resizeListener);
function updateScrollMsg(){
$('#msgS').html( $(document).scrollTop() +' // ' + $(".menu").offset().top );
}
function updateMediaMsg(){
var winmed = window.matchMedia("(max-width: 500px)");
var medmsg = (winmed.matches) ? '< 500' : '> 500';
console.log(medmsg);
$('#msgM').html(medmsg);
}
.menu{background:green;text-align:center;}
.content{height:200vh;background:palegreen;text-align:center;}
.hidden-logo{position:fixed;top:1vh;right:1vw;padding:15px; background:pink;z-index:2;}
#msgS{position:fixed;top:0;left:0;padding:10px;background:wheat;z-index:2;}
#msgM{position:fixed;top:40px;left:0;padding:10px;background:lightblue;z-index:2;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="menu">Menu Div</div>
<div class="content">Lengthy content Div..<br><br><br><br>100<br></div>
<div class="hidden-logo">LOGO</div>
<div id="msgS"></div>
<div id="msgM"></div>
Update:
Sorry, I had the media query a bit backwards myself - I think you want the logo to display when the screen-size is < 900px and to be hidden if wider than 900px, yes?
I added a msgM div so you can watch the media query kick-in -- but getting the best width for the demo was a bit of a challenge. I finally settled at 500px as a width that can be demoed (StackOverflow resizes its StackSnippets container as the browser window resizes, which throws things into confusion at each of their resize breakpoints)

Remove image from span on screen resize | jQuery

I am trying to add and remove images from span dependable on screen size.
I have 1 event handler to check the screen size and fire one of the functions if condition is true.
Here is my event handler:
jQuery(window).resize(function() {
var innerWidth = window.innerWidth;
if (innerWidth < 1000) {
ApplyIconsToMobileNav();
console.log("apply icons hit");
} else if (innerWidth > 1000) {
RemoveIconsDesktopNav();
console.log("removed icons hit");
}
});
Here is my apply icons function:
function ApplyIconsToMobileNav() {
var Categories = jQuery(".nav-menu > .nav-mobile > .nav-item > a").find("span:first-of-type");
jQuery(Categories).each(function() {
var Category = jQuery(this).text();
if(Category == "E-Liquid") {
jQuery(this).html("<img src='/media/wysiwyg/purple_icons/e-liquid(32x32).png' />" + Category);
} else if (Category == "E-Cigarette Kits") {
jQuery(this).html("<img src='/media/wysiwyg/purple_icons/e-cigarette(32x32).png' />" + Category);
}
});
};
And here is my remove icons function:
function RemoveIconsDesktopNav() {
var CategoriesImg = jQuery(".nav-menu > .nav-mobile > .nav-item > a").find("span:first-of-type");
jQuery(CategoriesImg).each(function() {
jQuery("img", this).hide();
});
};
I have a lot more images in the navigation but pasted only relevant code. My event listener is working fine, so is the ApplyIconsToMobileNav() function, however, I can't get the RemoveIconsDesktopNav() to work. I know, that I can do exactly the same thing I did in the ApplyIconsToMobileNav() but add style of display: none to the image but I want to select all images from the selected span and hide/remove them.
I am not familiar with this syntax: jQuery("img", this).hide();
However, you could try the following: $(this).find('img').hide();
Alternatively, you can also use .toggle(); instead of .hide(); if you wish to alternate between show/hide.
Instead of jQuery use CSS Media Queries. eg-
This CSS will work only when screen is than 767px that is a normal mobile screen
#media (max-width: 767px){
.class_name img{
display: none;
}
}

How to change id of div element when browser resize?

I have this code
<div id="123"></div>
i want to change the id to 234 when the browser resized
<div id="234"></div>
I have use media query , but i think it is not possible
#media screen and (max-width: 479px) {
#123 {
}
}
You can do this easily with javascript or jQuery.
Here a example written in JS.
window.onresize = function(){
var div = document.getElementById("aaa");
if(div){
div.setAttribute("id", "bbb");
}
}
#aaa {
font-size: 10px;
}
#bbb {
font-size: 10em;
}
<div id="aaa">Resize</div>
Im not sure what you are trying to do but this can be solved with window.onresize
You generally shouldn't be changing your element IDs around but if you want to you will need some logic in the onresize function to deduce which ID your element will have when you resize your window.
You're right! It's not possible to do with CSS, but it can be possible to do with JavaScript &/or jQuery. Try this using jQuery:
$(window).on('resize',function() {
$('#123').attr('id','234');
});
The problem with the code above, is that it's a 1x only change. You could never re-target that id after the first resize. So after the browser detects that it has been resized by 2-3 pixels, then the JS will break.
The real question is, why would you want to change an id on resize? It would be better to change an HTML 5 data-* attribute, like: data-id. This allows you to be able to change it repeatedly, using the #myUniqueId attribute. Then your code should continue to run continuously, for as long as the window is being resized.
Here is a jsfiddle for this code:
HTML:
<div id="myUniqueId" data-id="123"></div>
<div id="output"></div>
jQuery:
$(window).resize(function() {
var id = $('#myUniqueId').attr('data-id');
id++;
$('#myUniqueId').attr('data-id',id);
// Double check: what is my id?
var myId = $('#myUniqueId').attr('data-id');
$('#output').html(myId);
});
I use similiar code so you can use different css for mobile or desktop... However it completely irritates me.
This way you use the same id or class. But depending on screen size it will do something different.
#media not all and (min-width:999px){
/* Big Screen */
body {background-color:green; }
#id { background-color:red}
}
#media all and (min-width:1000px)
{
/* Smaller Screen */
body {background-color:blue; }
#id { background-color:grey}
}
Notice how when you manually re size the screen with your mouse the color changes....to the smaller css automatically.
No jQuery answer
window.onresize = function(event) {
if(document.getElementById('123') != null)
document.getElementById('123').id = '234';
};
Just be careful id 234 is not assigned to another element, however you should not be changing your id for changing styles as it should be done by adding and removing css classes.
I hope this one work for you.
//detect window resize
$(window).resize(function() {
//test if window width is below 479
$(window).width() < 479 ? small() : big();
//small function is called when window size is smaller than 479
function small(){
//edited from $( "#id_changer" ).append( "<div id='123'>123</div>" );
document.getElementByID('id_changer').innerHTML = "<div id='123'>123</div>";
}
//big function is called when window size is bigger than 479
function big(){
//edited from $( "#id_changer" ).append( "<div id='234'>234</div>" );
document.getElementByID('id_changer').innerHTML = "<div id='234'>234</div>";
}
});
<body>
<div id="id_changer"></div>
</body>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script src="test.js"></script>

How to append html element one time when specific screen resolution range occurs?

My html:
<div id="log">
</div>
My jQuery:
$(function() {
var win = $(window);
resizeHandler();
win.resize(resizeHandler);
function resizeHandler() {
if (win.width() <= 700) {
$("#log").append("<div>" + "success" + "</div>");
}
}
});
I want that when a specific screen resolution range occurs, the <div>success</div> element would be displayed one time in the "log" div element. For example: from 1 px to 700 px screen resolution the success must be displayed in the "log" div element one time, and when the screen resolution is out of the 1 px to 700 px range the <div>success</div> must be removed from the "log" div element. How should the code look like?
$(function() {
var win = $(window);
resizeHandler();
win.resize(resizeHandler);
function resizeHandler() {
if (win.width() >= 700) {
if ($('#log').children().length == 0)
$("#log").append("<div class='suc'>" + "success" + "</div>");
} else {
$('.suc').remove();
}
}
});
If you really want to append just one element. But, i would use media queries too, and hide/show desired element...
Based on information provided in the comments, you want a simple media query. No JS required. If that's what you really needed to do then #nevermind's answer was perfect.
Just change your code like this.
HTML:
<div id="log">
<div id="success">Success</div>
</div>
CSS:
#success {
display: none;
}
#media only screen and (max-width: 700px) {
#success {
display: block;
}
}
You could create a boolean variable and set it to true when appending
+ create an else statement in your resizeHandler to cope with the other screensizes.
But in a real world example i would have solved this issue by using CSS mediaqueries.

Scroll event background change

I am trying to add a scroll event which will change the background of a div which also acts as the window background (it has 100% width and height). This is as far as I get. I am not so good at jquery. I have seen tutorials with click event listeners. but applying the same concept , like, returning scroll event as false, gets me nowhere. also I saw a tutorial on SO where the person suggest use of array. but I get pretty confused using arrays (mostly due to syntax).
I know about plugins like waypoints.js and skrollr.js which can be used but I need to change around 50-60 (for the illusion of a video being played when scrolled) ... but it wont be feasible.
here is the code im using:-
*
{
border: 2px solid black;
}
#frame
{
background: url('1.jpg') no-repeat;
height: 1000px;
width: 100%;
}
</style>
<script>
$(function(){
for ( i=0; i = $.scrolltop; i++)
{
$("#frame").attr('src', ''+i+'.jpg');
}
});
</script>
<body>
<div id="frame"></div>
</body>
Inside your for loop, you are setting the src attribute of #frame but it is a div not an img.
So, instead of this:
$("#frame").attr('src', ''+i+'.jpg');
Try this:
$("#frame").css('background-image', 'url(' + i + '.jpg)');
To bind a scroll event to a target element with jQuery:
$('#target').scroll(function() {
//do stuff here
});
To bind a scroll event to the window with jQuery:
$(window).scroll(function () {
//do stuff here
});
Here is the documentation for jQuery .scroll().
UPDATE:
If I understand right, here is a working demo on jsFiddle of what you want to achieve.
CSS:
html, body {
min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
display: block;
position: fixed; /* Set this to fixed to lock that element on the position */
width: 300px;
height: 300px;
z-index: -1; /* Keep the bg frame at the bottom of other elements. */
}
Javascript:
$(document).ready(function() {
switchImage();
});
$(window).scroll(function () {
switchImage();
});
//using images from dummyimages.com for demonstration (300px by 300px)
var images = ["http://dummyimage.com/300x300/000000/fff",
"http://dummyimage.com/300x300/ffcc00/000",
"http://dummyimage.com/300x300/ff0000/000",
"http://dummyimage.com/300x300/ff00cc/000",
"http://dummyimage.com/300x300/ccff00/000"
];
//Gets a valid index from the image array using the scroll-y value as a factor.
function switchImage()
{
var sTop = $(window).scrollTop();
var index = sTop > 0 ? $(document).height() / sTop : 0;
index = Math.round(index) % images.length;
//console.log(index);
$("#frame").css('background-image', 'url(' + images[index] + ')');
}
HTML:
<div id="frame"></div>
Further Suggestions:
I suggest you change the background-image of the body, instead of the div. But, if you have to use a div for this; then you better add a resize event-istener to the window and set/update the height of that div with every resize. The reason is; height:100% does not work as expected in any browser.
I've done this before myself and if I were you I wouldn't use the image as a background, instead use a normal "img" tag prepend it to the top of your page use some css to ensure it stays in the back under all of the other elements. This way you could manipulate the size of the image to fit screen width better. I ran into a lot of issues trying to get the background to size correctly.
Html markup:
<body>
<img src="1.jpg" id="img" />
</body>
Script code:
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200) {
// function goes here
$('img').attr('src', ++count +'.jpg');
}
});
});
I'm not totally sure if this is what you're trying to do but basically, when the window is scrolled, you assign the value of the distance to the top of the page, then you can run an if statement to see if you are a certain point. After that just simply change run the function you would like to run.
If you want to supply a range you want the image to change from do something like this, so what will happen is this will allow you to run a function only between the specificied range between 200 and 400 which is the distance from the top of the page.
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200 && topPage < 400) {
// function goes here
$('#img').attr('src', ++count +'.jpg');
}
});
});

Categories

Resources