jQuery Dynamic Background-Postion for iPhone - javascript

Forgive me, I am a total n00b with javascript! I have a complicated request that I've been trying to put together for hours I think I have the pieces, but I have a poor understanding of javascript and jQuery syntax, can someone help me put this together?
First, this code should detect via UserAgent string if the device is an iPhone (Note: I'm not sure if this works for all mobile devices... any suggestions for better conditional statements that will catch ALL iPads, iPhones, etc. - anything that uses viewport rather than scrollbars)
<script type="text/javascript">
jQuery(document).ready(function(){
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
{
// do stuff
}
else
{
// do nothing
}
}
</script>
Next piece of the puzzle is detecting the height of the viewport. It's important that this script be conditional and apply only to devices that utilize viewport and NOT scrollbars, otherwise I screw the site up for non-mobile users. I only need to alter background-position on the y axis, trying to prevent the background image from disappearing when mobile users slide the viewport.
var viewportHeight = $(window).height();
I found this snippet of code that utilizes the "parralax" effect - where scrolling your position affects the background-position.
$(function(){
var yAdd = 0;
var scrollInterval = setInterval(function(){
yAdd++;
if(yAdd >= 920){
xAdd = 0;
}
$('#body').css('background-position',xAdd + 'px 100%');
},10);
}); }
Can someone help me stitch all of this together... PLEASE?!
I'm thinking it should look something like this:
<script type="text/javascript">
jQuery(document).ready(function(){
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
$(function(){
var viewportHeight = $(window).height();
var yAdd = 0;
var scrollInterval = setInterval(function(){
yAdd++;
if(yAdd >= 920){
yAdd = 0;
}
$('#body').css('background-position',yAdd + 'px 100%');
},10);
}); }
}
else
{
''
}
}
</script>

This might not be exactly what your looking for but you can detect iphone and ipad and ipod devices through CSS like this
<link rel="stylesheet" type="text/css" href="css/iphone.css" media="only screen and (max-device-width: 480px)" />
<link rel="stylesheet" media="only screen and (min-device-width: 768px) and (max-device-width: 1024px)" href="css/ipad.css" type="text/css" />
But I kno you need it through jQuery here is what you might do instead
jQuery(document).ready(function(){
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
// do something
} else {
//do this
}
});
the only problem is this code is not specific to iPhone, iPad, iPod and so on
as far as the background-image Fixed doesn't work I know you know that makes sense why it doesn't but it sucks and I have not explored a solution for this

I don't have an official answer for this yet, but I'm CLOSE... Read Over here
https://stackoverflow.com/questions/4719469/patching-this-code-to-apply-dynamic-iphone-background-position
I've found a way to dynamically set the "top: x" property based on scroll position (at least it works on my iPhone)... but I still need help putting it all together!

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)

Disable javascript based on screen size

Okay so this maybe no possible but i think it is, i'm completely new to this so what iv'e tried might obviously not work but i didn't know at the time. My sites mobile responsive with no separate webpage for mobile sites so putting the code into a page separately won't work either.
iv'e tried:
<style>
#media screen and (max-width: 720px) {
#div {
display:none;
}
}
</style>
<div id="div">
<script type="text/javascript">
var adfly_id = ID;
var popunder_frequency_delay = 0;
</script>
<script src="https://cdn.adf.ly/js/display.js"></script>
</div>
Which didn't work. Iv'e seen this code somewhere on here
if(screen.width < 720) {
// do any 720 width stuff here, or simply do nothing
return;
} else {
// do all your cool stuff here for larger screens
}
But i don't know how i would put the adfly code into it.
EDIT:
Thanks to those who replied, iv'e got it Praveen Kumar answer worked, while weirdly it still loads the ads on the desktop regardless of the resolution it works perfect on mobiles... Siguza i'll give yours ago so people know for future reference. and i'll edit again...
EDIT II:
For future reference, Siguza's method also works so if anyone else stumbles upon this then you can take your pic on who's to use. Also Praveen Kumar method works with shortest ads too for anyone that might use them instead of adfly below is what i use.
<script type="text/javascript">
if(screen.width < 720) {
var adfly_id = null;
var popunder_frequency_delay = null;
} else {
// do all your cool stuff here for larger screens
var adfly_id = ID;
var popunder_frequency_delay = 0;
}
</script>
<script src="https://cdn.adf.ly/js/display.js"></script>
<script type="text/javascript">
if(screen.width < 720) {
//screens bigger than 720
} else {
//shortest advertisement code
}
</script>
Replace this line:
<script src="https://cdn.adf.ly/js/display.js"></script>
with this:
<script>
if(screen.width >= 720) {
document.head.appendChild(document.createElement('script')).src = 'https://cdn.adf.ly/js/display.js';
}
</script>
This will simply create a <script> tag, set its src attribute to https://cdn.adf.ly/js/display.js, and add it to the <head> tag of your document.
Just in JavaScript instead of plain HTML.
Note that I'm relying on HTML 5 here, but so are you in your question (<script> and <style> not needing a type attribute).
Edit:
This approach appears to fail on scripts that use document.write (which, IMO, is bad practice).
You can work around this by using document.write yourself:
<script>
/* you can put your adfly_id code right here */
if(screen.width >= 720) {
document.write('<script src="https://cdn.adf.ly/js/display.js"><'+'/script>');
}
</script>
Note that you must split the </script> tag in the string, or it will close the surrounding script tag, causing a syntax error.
Could be a hack-job. If this works only if you have a valid adfly_id, then do this:
if(screen.width < 720) {
var adfly_id = null;
var popunder_frequency_delay = null;
} else {
// do all your cool stuff here for larger screens
var adfly_id = ID;
var popunder_frequency_delay = 0;
}
This might fail the adfly stuff you are trying to initialize.
But the right way to do this is:
if(screen.width < 720) {
// Bye bye.
} else {
// do all your cool stuff here for larger screens
require("awesome.js");
}
ps: The require() function here is a pseudo function that would include and activate the JavaScript file. A sample of that code would be:
function loadScript(url, callback) {
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}

$(window).resize(); not working as expected [duplicate]

This question already has answers here:
$(window).resize(); doesn't work
(5 answers)
Closed 7 years ago.
I want on set of functionality to be used on screen sizes larger than 768px and another set to be used on everything smaller than that. I need the .resize() so I can know when a user is turning their tablet or phone between landscape and portrait views.
The code on the inside of the .resize() event works fine if i refresh the page but it's as if the event isn't being triggered. Any thoughts?
<script>
jQuery(document).ready(function($){
function mobileFilterMenu(){
var screenTest = $(window).width();
if (screenTest >= 769){
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop(),
elementOffset = $('.inventory-search > .col-md-9').offset().top,
distance = (elementOffset - scrollTop);
if(distance <= 0){
$('.filter-form').css('top', Math.abs(distance));
}else{
$('.filter-form').css('top', 0);
}
});
}else{
var vHeight = $(window).height() - $('#switch').height() - $('#primary-menu-toggle').height();
$('.filter-form').css('height', vHeight + 'px');
vTextHeight = vHeight - 20;
$('.wpv-filter-form').css('height', vTextHeight + 'px');
objNegHeight = (vHeight * -1) + 50;
$('.filter-form').css('top', objNegHeight + 'px');
var i;
$('#switch').click(function(){
if (i === 0){
$('.filter-form').css('top', objNegHeight + 'px');
i++;
}else{
$('.filter-form').css('top', '50px');
i = 0;
}
});
}
}
mobileFilterMenu();
$(window).resize(mobileFilterMenu());
});
</script>
Just change this part of your code. This should fix your problem.
$(window).resize(mobileFilterMenu);
Instead of passing mobileFilterMenu(), pass this mobileFilterMenu
The parameter inside the $window.resize should have a function not a function call.
Hope this solves your issue.
You should use media queries to apply CSS based on viewport dimensions not code!
Media queries enable us to create a responsive experience, where
specific styles are applied to small screens, large screens and
anywhere in between. The media query syntax allows for the creation of
rules that can be applied depending on device characteristics.
#media (query) {
/* CSS Rules used when query matches */
}
While there are several different items we can query on, the ones used
most often for responsive web design are min-width, max-width,
min-height and max-height.
<link rel="stylesheet" media="(max-width: 640px)" href="max-640px.css">
<link rel="stylesheet" media="(min-width: 640px)" href="min-640px.css">
<link rel="stylesheet" media="(orientation: portrait)" href="portrait.css">
<link rel="stylesheet" media="(orientation: landscape)" href="landscape.css">
<style>
#media (min-width: 500px) and (max-width: 600px) {
h1 {
color: fuchsia;
}
.desc:after {
content:" In fact, it's between 500px and 600px wide.";
}
}
</style>
https://developers.google.com/web/fundamentals/layouts/rwd-fundamentals/use-media-queries?hl=en#apply-media-queries-based-on-viewport-size

Do not execute jQuery script if CSS is of particular value

On my website, I have a sidebar DIV on the left and a text DIV on the right. I wanted to make the sidebar follow the reader as he or she scrolls down so I DuckDuckGo'ed a bit and found this then modified it slightly to my needs:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function(){
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
$window.scroll(function(){
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
})
});
});//]]>
</script>
And it works just like I want it to. However, my website uses Skeleton framework to handle responsive design. I've designed it so that when it goes down to mobile devices (horizontal then vertical), sidebar moves from being to the left of the text to being above it so that text DIV can take 100% width. As you can probably imagine, this script causes the sidebar to cover parts of text as you scroll down.
I am completely new to jQuery and I am doing my best through trial-and-error but I've given up. What I need help with is to make this script not execute if a certain DIV has a certain CSS value (i.e. #header-logo is display: none).
Ideally, the script should check for this when user resizes the browser, not on website load, in case user resizes the browser window from normal size to mobile size.
I imagine it should be enough to wrap it in some IF-ELSE statement but I am starting to pull the hair out of my head by now. And since I don't have too much hair anyway, I need help!
Thanks a lot in advance!
This function will execute on window resize and will check if #header-logo is visible.
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
});
I think you need to check this on load to, because you don't know if the user will start with mobile view or not. You could do something like this:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
}).resize();
This will get executed on load and on resize.
EDIT: You will probably need to turn off the scroll function if #header-logo is not visible. So, instead of create the function inside the scroll event, you need to create it outside:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
function myScroll() {
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
}
$window.on('scroll', myScroll);
} else {
$(window).off('scroll', myScroll);
}
});
Didn't test it, but you get the idea.
$("#headerLogo").css("display") will get you the value.
http://api.jquery.com/css/
I also see you only want this to happen on resize, so wrap it in jquery's resize() function:
https://api.jquery.com/resize/

Spry like slide effect

I am not sure if Spry is just smoother than jQuery but I can never get my animations as smooth as http://labs.adobe.com/technologies/spry/samples/effects/slide_sample.html
I perform my animations as follows:
$("#button").click(function (e) {
$("#thediv").css('margin-left',$(window).width + 10 + 'px');
$("#thediv").animate({
'margin-left' : '0'
},100);
});
I have tried playing with the easing, lowering the framerate using a plugin, adjusting the ms. Does Spry do anything different? As far as Im aware it manipulates the DOM like jQuery. What are ideal animation settings to create smooth "slide from left" div transitions. The web app is for a mobile phone and the div switcing is for switching between views.
Yes you can get exact effect: Working demo :) http://jsfiddle.net/FjgjE/ or http://jsfiddle.net/YWcgw/
Use these js and css files and rest html and full js code is in demo.
Please lemme know if I missed anything!
Hope it helps your cause :) rest feel free to play around with the demo.
scripts
<link href="http://labs.adobe.com/technologies/spry/css/samples.css" rel="stylesheet" type="text/css" />
<script src="http://labs.adobe.com/technologies/spry/includes/SpryEffects.js" type="text/javascript"></script>
code
var animation_start = function(){
var button = document.getElementById('animation_button');
if (button){
button.disabled = true;
button.style.backgroundColor = '#FFF';
}
}
var animation_stop = function(){
var button = document.getElementById('animation_button');
if (button){
button.disabled = false;
button.style.backgroundColor = '';
}
}
var slide_func = new Spry.Effect.Slide('slideIt', {toggle:true, setup: animation_start, finish: animation_stop});​

Categories

Resources