load iframe on scroll down - javascript

i have a page with an iframe...
currently i used this code to load iframe on click..
here is my code
$('.a').click(function(){
var iframe = $("#b");
iframe.attr("src", iframe.data("src"));
});
html:
<button class='a'>Load</button>
<iframe id='b' src='' data-src='index.php'></iframe>
but i also i want to load iframe on scroll down (500px from top)
can someone please help me how i can do this...
Thanks

Try this:
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > 500) {
var iframe = $("#b");
iframe.attr("src", iframe.data("src"));
}
});
If you want to only load one time after scroll with more than 500
you can add flag and set it to false on page load. Then set it true inside scrolling event and check for this flag before you load iframe
Example:
var isLoaded = false;
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > 500) {
if(!isLoaded){
var iframe = $("#b");
iframe.attr("src", iframe.data("src"));
isLoaded = true;
}
}
});

The idea is to add a callback to the scroll event dispatched on the window object every time the user scrolls the page. This callback is used to load the iframe if it's not loaded yet and if the scroll value is higher than 500px.
(function () {
var iframeLoaded = false;
function loadIframeOnScroll() {
if (window.scrollY >= 500 && !iframeLoaded) {
loadIframe();
}
};
function loadIframe() {
if (!iframeLoaded) {
var $iframe = $('#b');
$iframe.attr('src', $iframe.data('src'));
window.removeEventListener('scroll', loadIframeOnScroll);
iframeLoaded = true; // could be placed in the onload callback of the iframe
}
}
window.addEventListener('scroll', loadIframeOnScroll);
document.querySelector('.a').addEventListener('click', loadIframe);
})();

Related

only scroll to bottom if user not scrolling

I find myself getting frustrated with JS yet again! please help!
below is some code I am using for a simple chat app, that refreshes the content from a text file via an AJAX request. At the same time it scrolls to the bottom of the window. I want it so if the user scrolls up to catch up it doesnt keep interupting this behavour by sending them down to the bottom when it refreshes. How could I do this.
<script>
$(function() {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh,3000);
$.post('pollchat.php', function(data) {
$('#content_div_id').html(data);
var wtf = $('#content_div_id');
var height = wtf[0].scrollHeight;
wtf.scrollTop(height);
});
}
</script>
Any help greatly appreciated.
See How I have used current scroll position and counted that whether user has scrolled or not..
$(function() {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh, 1000);
var wtf = $('#content_div_id');
var currentScrollPos = wtf.scrollTop();
var elementHeight = wtf[0].scrollHeight;
var scroll = false;
//User has scrolled, don't set scroll
if (wtf.height() + currentScrollPos >= elementHeight) {
scroll = true;
}
var data = $('#content_div_id').html();
data += "Some Text<br/>";
$('#content_div_id').html(data);
if (scroll) {
var height = wtf[0].scrollHeight;
wtf.scrollTop(height);
}
}
#content_div_id {
max-height: 100px;
overflow-y: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content_div_id">
Some Text
<br/>Some Text
<br/>Some Text
<br/>Some Text
<br/>
</div>
UPDATE:
Try this code, you probably need to fix one or two things .. but have a look at the code and get an idea
$(function() {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh,3000);
$.post('pollchat.php', function(data) {
var wtf = $('#content_div_id');
var currentScrollPos = wtf.scrollTop();
var elementHeight = wtf[0].scrollHeight;
var scroll = false;
//User has scrolled, don't set scroll
if (wtf.height() + currentScrollPos >= elementHeight) {
scroll = true;
}
$('#content_div_id').html(data);
if (scroll) {
var height = wtf[0].scrollHeight;
wtf.scrollTop(height);
}
});
}

Script not running in modal window

I've got a script that changes the background when an anchor touches the top of the page.
https://jsfiddle.net/u9pexc4v/
var targetOffset = $("#anchor-point").offset().top;
var $w = $(window).scroll(function () {
if ($w.scrollTop() > targetOffset) {
$(".projectTitle").addClass("topper");
} else {
$(".projectTitle").removeClass("topper");
}
});
However, it does not work when it's inside the modal window.
https://jsfiddle.net/qhrmtass/
I believe you need to attach the scroll event to the element that's scrolling.
$('.remodal').scroll(function () {
console.log('Scrolling...');
if ($('.remodal').scrollTop() > targetOffset) {
$(".projectTitle").addClass("topper");
} else {
$(".projectTitle").removeClass("topper");
}
});
Updated fiddle

Windows resize event not properly detected

I have a navigation menu that should stay fixed at the top of the page using the sticky.js plugin for window-widths equal or larger than 992 px. For smaller windows, it should just go with the flow of the site. Now, as this is a responsive website, I would like to implement a dynamic window width detection when the window is resized.
The following code does not seem to correctly detect the resize event. I have to reload the page to stick / unstick the navbar at the correct width:
$(document).ready(function() {
var currentWindow = $(window);
function checkWidth() {
var windowSize = currentWindow.width();
if (windowSize >= 992) {
// Sticky.js
$('.navbar').sticky({
topSpacing: 0,
getWidthFrom: '.upper-header',
responsiveWidth: true
});
} else {
alert('Window is smaller');
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});
Would appreciate your guidance.
You need to unstick the navbar when the window shrinks.
$(document).ready(function() {
var currentWindow = $(window);
var stuck = false; // So we only call the plugin when necessary
function checkWidth() {
var windowSize = currentWindow.width();
if (windowSize >= 992 && !stuck) {
// Sticky.js
$('.navbar').sticky({
topSpacing: 0,
getWidthFrom: '.upper-header',
responsiveWidth: true
});
stuck = true;
} else if (windowSize < 992 && stuck) {
alert('Window is smaller');
$('.navbar').unstick();
stuck = false;
}
}
// Execute on load
checkWidth();
// Bind event listener
currentWindow.resize(checkWidth);
});

Why jQuery doing unwanted multiple actions of single command?

When i resize browser the it gives multiple alerts. I used "return false" not working.
If I used unbind()/unbind('resize') then it works but it creates an other problem- the resize() function stops working from second time browser/window resize.
My code-
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
alert($(".myclass").parent().width());
$(window).bind('resize',function() {
alert($(".myclass").parent().width());
});
});
</script>
<section class="myclass"></section>
This is not an issue with jQuery, but on the browser's implementation of resize.
Depending which browser you use it may trigger intermediate resizes, or a resize when your mouse is released only.
Because the resize triggers everytime the browser changes.
If you are resizing 100 pixels it can trigger up to 100 times.
Something like this should work and trigger only once you stopped resizing the window:
var resizing = false, stopedResizing = true;
$(window).bind('resize',function() {
if(!resizing){
console.log("started resizing. Width = " + $(".myclass").parent().width());
resizing = true;
}
stopedResizing = false;
setTimeout(function(){
if(!stopedResizing){
stopedResizing = true;
setTimeout(function(){
if(stopedResizing && resizing){
resizing = false;
console.log('Stoped resizing. Width = ' + $(".myclass").parent().width());
}
}, 500);
}
}, 500);
});
You could do something like:
$(document).ready(function(e) {
alert($(".myclass").parent().width());
var lastTime = 0;
$(window).bind('resize',function() {
var currentTime = new Date().time();
if(currentTime > lastTime + 5000)
alert($(".myclass").parent().width());
lastTime = currentTime;
});
});
...so that it will only fire on resizes at least 5 seconds apart. Normally though, you'd want to act when resizing stops, not when it starts.
This code fires ones on mouseover of the window after the a resize event as occurred.
$(document).ready(function() {
var windowResized = false;
function callFunction() {
console.log("I am called once after window resize");
}
$(window).mouseover(function() {
if (windowResized == true) {
callFunction();
windowResized = false;
}
})
$(window).resize(function() {
windowResized = true;
});
})

jQuery trigger action when a user scrolls past a certain part of the page

Hey all, I need a jQuery action to fire when a user scrolls past certain locations on the page. Is this even possible with jQuery? I have looked at .scroll in the jQuery API and I don't think this is what I need. It fires every time the user scrolls, but I need it to fire just when a user passes a certain area.
Use the jquery event .scroll()
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
http://jsfiddle.net/babumxx/hpXL4/
Waypoints in jQuery should do it:
http://imakewebthings.github.com/jquery-waypoints/
$('#my-el').waypoint(function(direction) {
console.log('Reached ' + this.element.id + ' from ' + direction + ' direction.');
});
jQuery waypoints plugin documentation: http://imakewebthings.com/waypoints/guides/jquery-zepto/
To fire any action only once on a single page I have modified jondavid's snippet as following.
jQuery(document).ready(function($){
$triggered_times = 0;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test && $triggered_times == 0 ) {
//do your stuff over here
$triggered_times = 1; // to make sure the above action triggers only once
}
});
})
Scroll down to Run code snippet
Here you can check example of working code snippet;
jQuery(document).ready(function($){
$triggered_times = 0;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test && $triggered_times == 0 ) {
alert('This alert is triggered after you have scroll down to 150px')
$triggered_times = 1; // to make sure the above action triggers only once
}
});
})
p {
height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p>scroll down this block to get an alert</p>
</body>

Categories

Resources