How to remove scrow follow javascript when screen width changes - php

I have a JavaScript code which is going to go on a WordPress CMS in the index.php file of my theme (see javascript code below). I have succeeded in making the scroll work, but when I resize the window (when the responsiveness sets in) the banner goes all the way to the left of my screen. I had thought that by disabling the JavaScript with a plain div tag, the responsiveness work. So I figured out that if I disable the JavaScript at that point when the width of the containing tag was less than 600 I could make it work (by simply removing the JavaScript). It does not work.
I am not sure that the JavaScript solution is the best solution. Can anyone help? Any suggestions will be welcomed...
<script type = "text/javascript" >
$(document).ready(function () {
var $sidebar = $(".follow-scroll"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 20;
$window.scroll(function () {
//disable javascript if width larget less than 600
if ($('.outern').width() < 600) {
return;
} else {
//enable scroll folowing feature otherwise
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 20
});
}
}
});
});
</script>
Thank you

jQuery's resize() listens for when the windows width/height changes.

Related

removing 'skrollr' on mobile screens

I am trying to remove the skrollr functions on mobile (max width 767px) screen.
I have the following code that (it is assumed) to stop skrollr on mobile but it doesn't work (I have tried putting it in a seperate, enquened file and put it in the skrollr code itself, no change)
JAVA code
$(function () {
// initialize skrollr if the window width is large enough
if ($(window).width() > 767) {
skrollr.init(yourOptions);
}
// disable skrollr if the window is resized below 768px wide
$(window).on('resize', function () {
if ($(window).width() <= 767) {
skrollr.init().destroy(); // skrollr.init() returns the singleton created above
}
});
});
code at the bottom of footer.php (to make skrollr work)
<script type="text/javascript">
skrollr.init({
forceHeight: false
});
</script>
<script type="text/javascript">
//http://detectmobilebrowsers.com/ + tablets
(function(a) {
if(/android|avantgo|bada\ ... )
{
//Add skrollr mobile on mobile devices.
document.write('<script type="text/javascript" src="js/skrollr.mobile.min.js"><\/script>');
}
})(navigator.userAgent||navigator.vendor||window.opera);
</script>
You are initializing skrollr in the footer.php regardless of the current window width. The condition in line 3 of your JAVASCRIPT file - if ($(window).width() > 767) { - does work, but skrollr is already initialized at this point by the javascript in your footer.php
I would recommend you to remove the initialization of skrollr in the footer.php file and modify your javascript code to something like this:
(function($) {
$(function () {
var skrollrInstance;
var onResize = function () {
var isMobile = $(window).width() <= 767;
if (!skrollrInstance && !isMobile) {
skrollrInstance = skrollr.init({
forceHeight: false
});
} else if(skrollrInstance && isMobile) {
skrollrInstance.destroy();
skrollrInstance = null;
}
};
$(window).on('resize', onResize);
onResize();
});
})(jQuery);
Fiddle: http://jsfiddle.net/erfvgx85/2/ (resize the "Result" frame to test it)
I have stored the current skrollrInstance in a separate variable. As you have commented, "// skrollr.init() returns the singleton (instance) created above", but it could be a performance issue if skrollr isn't initialized or already destroyed at this moment.
I also think that it's nicer to just have one place for the call of skrollr.init - otherwise we could forget to pass the same options (forceHeight: false) in another call. (like in your example)

Check Screen Width then all Urls on the page Redirect to mobile if

I am a newbie to jQuery / javascript and I had this working without checking the window size first. Then messed around with it and can not get it to work. The redirect is supposed to replace mysite.com/index.php?querystring with mysite.com/mobile.php?querystring if screen size is less then 699. Please help. Thank You.
This function seems to work exaclty how I need it but need to have onload with if screen size is less then.
$('a').each(function(index, a) {
var href = $(a).attr('href');
$(a).attr('href', 'http://mysite.com/mobile.php?redirect=' + href;)
}
}
//below is not working
function checkWidth() {
var windowSize = $(window).width();
if (windowSize <= 699) {
window.onload = function() {
/* onload code */
// Execute on load
//checkWidth();{
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].href = "http://mysite.com/mobile.php?redirect=" + anchors[i].href
/* function checkWidth() {
var windowSize = $(window).width();*/
}
}
If you intend on using jQuery, this should work:
$(document).ready(function() {
var window_width = $(window).width();
if( window_width < 699 ) {
$('a').each(function(index, a) {
var href = $(a).attr('href');
$(a).attr('href', 'http://mysite.com/mobile.php?redirect=' + href;
});
}
});
This is really something you should be doing server-side. Because someone isn't exactly going to be switching the device over the course of the session, you should check the device when they first visit the site, and then create a session variable storing it. Then, on every new page have the server check the variable and use it to determine which links to put in. If you're content with doing it client-side, though, Ryan Pilbeam's answer should work.

how to load a diferrent php file dynamically based on the browser window's width using jQuery or any other method

Hello friends a very novice question as I am very new to programming.
I was browsing the web and found a method to dynamically load a CSS file based on the browser width.
jQuery
function adjustStyle(width) {
width = parseInt(width);
if (width < 701) {
$("#size-stylesheet").attr("href", "css/narrow.css");
} else if ((width >= 701) && (width < 900)) {
$("#size-stylesheet").attr("href", "css/medium.css");
} else {
$("#size-stylesheet").attr("href", "css/wide.css");
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
HTML
<link rel="stylesheet" type="text/css" href="main.css" />
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="narrow.css" />
I want to know, can I use the same to load a php file?
If yes what will be the code look like?
I think we will be required to use something like <?php require_once('http://mysite.com/layouts/ipad.php'); ?> but how do I code it?
Kindly help.
Regards
I want to know, can I use the same to load a php file?
If by "load a php file" you mean load a different page where you'll define different pages for different conditions (widths, whatever), then you can load different pages by setting window.location equal to the desired page. This will replace the current page with the one you specify.
I don't think you should do this every time the window is resized though. If you must do it at least check whether the new size actually requires a change rather than repeatedly reloading it regardless.
Following is similar to your existing code:
function setLocation(url) {
if (window.location.href.indexOf(url) === -1)
window.location = url;
}
function reloadPage(width) {
width = parseInt(width);
if (width < 701) {
setLocation("yournarrowpage.php");
} else if (width < 900) {
setLocation("yourmediumpage.php");
} else {
setLocation("yourwidepage.php");
}
}
$(function() {
reloadPage($(this).width());
$(window).resize(function() {
reloadPage($(this).width());
});
});
You don't have to reload the entire page each time though, you can reload just certain sections using ajax. For that you could do something similar to the above except instead of setting window.location you'd use jQuery's .load() method:
function setLocation(url) {
$("selector for the element to reload").load(url);
}
I suspect what you're actually wanting to do is redirect the user to a different page based on browser or resolution.
$(document).load(function() {
var $width = $(window).width()
if($width < 701)
window.location = 'narrow.php'
else if($width < 900)
window.location = 'medium.php'
else
window.location = 'wide.php'
})
You could easily make the same function run on window resize, although it may not work as well as you hope in practice.
Edit: If you're just doing this for iPads specifically (which you shouldn't):
if(stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla/5.0(iPad;')) {
// probably an iPad
require('ipad.php');
//Or maybe the below might serve you better:
/*
header('Location:ipad.php');
die();
*/
}
This is a good starting place for the css question: http://topsecretproject.finitestatemachine.com/2009/09/how-to-load-javascript-and-css-dynamically-with-jquery/
And for loading php, see Including a php file dynamically with javascript and jquery
if (width < 701) {
$.get('yourlayoutfor701.php', function(data) {
$('#your_layout').html(data);
});
}
hope this might help you, but not a good practice

Jquery overlay from checking php variable

I have this script from JQuery.
<script>
// create custom animation algorithm for jQuery called "drop"
$.easing.drop = function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
};
// loading animation
$.tools.overlay.addEffect("drop", function(css, done) {
// use Overlay API to gain access to crucial elements
var conf = this.getConf(),
overlay = this.getOverlay();
// determine initial position for the overlay
if (conf.fixed) {
css.position = 'fixed';
} else {
css.top += $(window).scrollTop();
css.left += $(window).scrollLeft();
css.position = 'absolute';
}
// position the overlay and show it
overlay.css(css).show();
// begin animating with our custom easing
overlay.animate({ top: '+=55', opacity: 1, width: '+=20'}, 400, 'drop', done);
/* closing animation */
}, function(done) {
this.getOverlay().animate({top:'-=55', opacity:0, width:'-=20'}, 300, 'drop', function() {
$(this).hide();
done.call();
});
}
);
$("img[rel]").overlay({
effect: 'drop',
mask: '#789'
});
</script>
Right now it works by me clicking on an image. Then the overlay comes up with whatever is in the div. However I want to take out clicking the image and just have the overlay come up with an if statement in PHP. any ideas...im not very good at js.
EDIT:
yes im using the JQuery plugin Easing. However the overlay works great...and the overlay works by clicking on an image with the rel attribute like this
<img src="http://farm4.static.flickr.com/3651/3445879840_7ca4b491e9_m.jpg" rel="#mies1"/>
However I don't want to click on the images I want it to come up automatically.
<?php if ($whatever) { ?>
$(document).ready(function() {
$("img[rel]").click();
});
<?php } ?>

Resize iframe height according to content height in it

I am opening my blog page in my website. The problem is I can give a width to an iframe but the height should be dynamic so that there is no scrollbar in the iframe, and it looks like a single page...
I have tried various JavaScript code to calculate the height of the content but all of them give an access denied permission error and is of no use.
<iframe src="http://bagtheplanet.blogspot.com/" name="ifrm" id="ifrm" width="1024px" ></iframe>
Can we use Ajax to calculate height or maybe using PHP?
To directly answer your two subquestions: No, you cannot do this with Ajax, nor can you calculate it with PHP.
What I have done in the past is use a trigger from the iframe'd page in window.onload (NOT domready, as it can take a while for images to load) to pass the page's body height to the parent.
<body onload='parent.resizeIframe(document.body.scrollHeight)'>
Then the parent.resizeIframe looks like this:
function resizeIframe(newHeight)
{
document.getElementById('blogIframe').style.height = parseInt(newHeight,10) + 10 + 'px';
}
Et voila, you have a robust resizer that triggers once the page is fully rendered with no nasty contentdocument vs contentWindow fiddling :)
Sure, now people will see your iframe at default height first, but this can be easily handled by hiding your iframe at first and just showing a 'loading' image. Then, when the resizeIframe function kicks in, put two extra lines in there that will hide the loading image, and show the iframe for that faux Ajax look.
Of course, this only works from the same domain, so you may want to have a proxy PHP script to embed this stuff, and once you go there, you might as well just embed your blog's RSS feed directly into your site with PHP.
You can do this with JavaScript.
document.getElementById('foo').height = document.getElementById('foo').contentWindow.document.body.scrollHeight + "px";
Fitting IFRAME contents is kind of an easy thing to find on Google. Here's one solution:
<script type="text/javascript">
function autoIframe(frameId) {
try {
frame = document.getElementById(frameId);
innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
objToResize = (frame.style) ? frame.style : frame;
objToResize.height = innerDoc.body.scrollHeight + 10;
}
catch(err) {
window.status = err.message;
}
}
</script>
This of course doesn't solve the cross-domain problem you are having... Setting document.domain might help if these sites are in the same place. I don't think there is a solution if you are iframe-ing random sites.
Here's my solution to the problem using MooTools which works in Firefox 3.6, Safari 4.0.4 and Internet Explorer 7:
var iframe_container = $('iframe_container_id');
var iframe_style = {
height: 300,
width: '100%'
};
if (!Browser.Engine.trident) {
// IE has hasLayout issues if iframe display is none, so don't use the loading class
iframe_container.addClass('loading');
iframe_style.display = 'none';
}
this.iframe = new IFrame({
frameBorder: 0,
src: "http://www.youriframeurl.com/",
styles: iframe_style,
events: {
'load': function() {
var innerDoc = (this.contentDocument) ? this.contentDocument : this.contentWindow.document;
var h = this.measure(function(){
return innerDoc.body.scrollHeight;
});
this.setStyles({
height: h.toInt(),
display: 'block'
});
if (!Browser.Engine.trident) {
iframe_container.removeClass('loading');
}
}
}
}).inject(iframe_container);
Style the "loading" class to show an Ajax loading graphic in the middle of the iframe container. Then for browsers other than Internet Explorer, it will display the full height IFRAME once the loading of its content is complete and remove the loading graphic.
Below is my onload event handler.
I use an IFRAME within a jQuery UI dialog. Different usages will need some adjustments.
This seems to do the trick for me (for now) in Internet Explorer 8 and Firefox 3.5.
It might need some extra tweaking, but the general idea should be clear.
function onLoadDialog(frame) {
try {
var body = frame.contentDocument.body;
var $body = $(body);
var $frame = $(frame);
var contentDiv = frame.parentNode;
var $contentDiv = $(contentDiv);
var savedShow = $contentDiv.dialog('option', 'show');
var position = $contentDiv.dialog('option', 'position');
// disable show effect to enable re-positioning (UI bug?)
$contentDiv.dialog('option', 'show', null);
// show dialog, otherwise sizing won't work
$contentDiv.dialog('open');
// Maximize frame width in order to determine minimal scrollHeight
$frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
contentDiv.offsetWidth + frame.offsetWidth);
var minScrollHeight = body.scrollHeight;
var maxWidth = body.offsetWidth;
var minWidth = 0;
// decrease frame width until scrollHeight starts to grow (wrapping)
while (Math.abs(maxWidth - minWidth) > 10) {
var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
$body.css('width', width);
if (body.scrollHeight > minScrollHeight) {
minWidth = width;
} else {
maxWidth = width;
}
}
$frame.css('width', maxWidth);
// use maximum height to avoid vertical scrollbar (if possible)
var maxHeight = $contentDiv.dialog('option', 'maxHeight')
$frame.css('height', maxHeight);
$body.css('width', '');
// correct for vertical scrollbar (if necessary)
while (body.clientWidth < maxWidth) {
$frame.css('width', maxWidth + (maxWidth - body.clientWidth));
}
var minScrollWidth = body.scrollWidth;
var minHeight = Math.min(minScrollHeight, maxHeight);
// descrease frame height until scrollWidth decreases (wrapping)
while (Math.abs(maxHeight - minHeight) > 10) {
var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
$body.css('height', height);
if (body.scrollWidth < minScrollWidth) {
minHeight = height;
} else {
maxHeight = height;
}
}
$frame.css('height', maxHeight);
$body.css('height', '');
// reset widths to 'auto' where possible
$contentDiv.css('width', 'auto');
$contentDiv.css('height', 'auto');
$contentDiv.dialog('option', 'width', 'auto');
// re-position the dialog
$contentDiv.dialog('option', 'position', position);
// hide dialog
$contentDiv.dialog('close');
// restore show effect
$contentDiv.dialog('option', 'show', savedShow);
// open using show effect
$contentDiv.dialog('open');
// remove show effect for consecutive requests
$contentDiv.dialog('option', 'show', null);
return;
}
//An error is raised if the IFrame domain != its container's domain
catch (e) {
window.status = 'Error: ' + e.number + '; ' + e.description;
alert('Error: ' + e.number + '; ' + e.description);
}
};
#SchizoDuckie's answer is very elegant and lightweight, but due to Webkit's lack of implementation for scrollHeight (see here), does not work on Webkit-based browsers (Safari, Chrome, various and sundry mobile platforms).
For this basic idea to work on Webkit along with Gecko and Trident browsers, one need only replace
<body onload='parent.resizeIframe(document.body.scrollHeight)'>
with
<body onload='parent.resizeIframe(document.body.offsetHeight)'>
So long as everything is on the same domain, this works quite well.
I just spent the better part of 3 days wrestling with this. I'm working on an application that loads other applications into itself while maintaining a fixed header and a fixed footer. Here's what I've come up with. (I also used EasyXDM, with success, but pulled it out later to use this solution.)
Make sure to run this code AFTER the <iframe> exists in the DOM. Put it into the page that pulls in the iframe (the parent).
// get the iframe
var theFrame = $("#myIframe");
// set its height to the height of the window minus the combined height of fixed header and footer
theFrame.height(Number($(window).height()) - 80);
function resizeIframe() {
theFrame.height(Number($(window).height()) - 80);
}
// setup a resize method to fire off resizeIframe.
// use timeout to filter out unnecessary firing.
var TO = false;
$(window).resize(function() {
if (TO !== false) clearTimeout(TO);
TO = setTimeout(resizeIframe, 500); //500 is time in miliseconds
});
The trick is to acquire all the necessary iframe events from an external script. For instance, you have a script which creates the iFrame using document.createElement; in this same script you temporarily have access to the contents of the iFrame.
var dFrame = document.createElement("iframe");
dFrame.src = "http://www.example.com";
// Acquire onload and resize the iframe
dFrame.onload = function()
{
// Setting the content window's resize function tells us when we've changed the height of the internal document
// It also only needs to do what onload does, so just have it call onload
dFrame.contentWindow.onresize = function() { dFrame.onload() };
dFrame.style.height = dFrame.contentWindow.document.body.scrollHeight + "px";
}
window.onresize = function() {
dFrame.onload();
}
This works because dFrame stays in scope in those functions, giving you access to the external iFrame element from within the scope of the frame, allowing you to see the actual document height and expand it as necessary. This example will work in firefox but nowhere else; I could give you the workarounds, but you can figure out the rest ;)
Try this, you can change for even when you want. this example use jQuery.
$('#iframe').live('mousemove', function (event) {
var theFrame = $(this, parent.document.body);
this.height($(document.body).height() - 350);
});
Try using scrolling=no attribute on the iframe tag. Mozilla also has an overflow-x and overflow-y CSS property you may look into.
In terms of the height, you could also try height=100% on the iframe tag.

Categories