Update div content in real time with jQuery - javascript

I'm pretty new to web design, and I wanted to make a rectangle which says "true" if the user has scrolled, and turn to "false" after one second has passed.
var hasScroll = false;
$(document).ready(function() {
$(window).scroll(function() {
hasScroll = true;
$("#rectangle").html(hasScroll.toString());
setTimeout(function() {
hasScroll = false;
}, 1000);
});
});
body { height: 800px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rectangle"></div>
However, even though the variable "hasScroll" changes exactly how I want, I can't seem to find a way to make the div show the hasScroll status in real-time.

You'll need to set the #rectangle's text again after the scrolling is done. You'll also probably want to set/clear a setTimeout that only runs once no scroll events have been triggered for 1000ms:
let scrollingTimeout;
const rectangle = document.querySelector('#rectangle');
$(window).scroll(function() {
if (scrollingTimeout) clearTimeout(scrollingTimeout);
else rectangle.textContent = 'true';
scrollingTimeout = setTimeout(function() {
console.log('setting text to false');
rectangle.textContent = 'false';
scrollingTimeout = null;
}, 1000);
});
body {
height: 800px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rectangle">abc</div>

It's very simple, Just put the same line $("#rectangle").html(hasScroll.toString()); after setting hasScroll = false;
For ex.,
var hasScroll = false;
$(document).ready(function() {
$(window).scroll(function() {
hasScroll = true;
$("#rectangle").html(hasScroll.toString());
setTimeout(function() {
hasScroll = false;
$("#rectangle").html(hasScroll.toString()); // To show false
}, 1000);
});
});

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);
}
});
}

vertical scroll two tables at the same time

I have two tables that must scroll together:
$('.vscroll').on('scroll', function (e) {
divTable1.scrollTop = e.scrollTop;
divTable2.scrollTop = e.scrollTop;
There's a little lag issue though. Table1 scrolls milliseconds before Table2.
I know scrollTop fires the scroll event, but is there a way to delay the scrolling of Table1 until Table2's scrollTop is also set?
Try using a setTimeout to trigger the scrolls, and then return false to cancel the original scrollevent:
var ignoreEvent = false;
$(".vscroll").on('scroll', function (e) {
if (!ignoreEvent) {
setTimeout(function() {
ignoreEvent = true;
table1.scrollTop = e.scrollTop;
table2.scrolLTop = e.scrollTop;
}, 100);
}
ignoreEvent = false;
return false; // cancels the original scroll event.
}
I'm using divs instead of tables but you get the idea
$("div").on("scroll",function(){
$("div:not(this)").scrollTop($(this).scrollTop());
});
DEMO

Wait until div is not visible to process next line

I need to write some code which is supposed to wait until a predefined div is no longer visible in order to process the next line. I plan on using jQuery( ":visible" ) for this, and was thinking I could have some type of while loop. Does anyone have a good suggestion on how to accomplish this task?
$( document ).ready(function() {
$(".scroller-right" ).mouseup(function( event ) {
alert('right');
pollVisibility();
});
});
function pollVisibility() {
if ($(".mstrWaitBox").attr("visibility")!== 'undefined') || $(".mstrWaitBox").attr("visibility") !== false) {
alert('inside else');
microstrategy.getViewerBone().commands.exec('refresh');
} else {
setTimeout(pollVisibility, 100);
}
}
$( document ).ready(function() {
$(".scroller-right" ).mouseup(function( event ) {
alert('right');
pollVisibility();
});
});
function pollVisibility() {
if (!$(".mstrWaitBox").is(":visible")) {
alert('inside if');
microstrategy.getViewerBone().commands.exec('refresh');
} else {
setTimeout(pollVisibility, 100);
}
}
div when not visible:
<div class=​"mstrWaitBox" id=​"divWaitBox" scriptclass=​"mstrDialogImpl" dg=​"1" ty=​"edt">​
</div>​
div when visible:
<div class=​"mstrWaitBox" id=​"divWaitBox" scriptclass=​"mstrDialogImpl" dg=​"1" ty=​"edt" visibility="visible">​
</div>​
You can use the setTimeout function to poll the display status of the div. This implementation checks to see if the div is invisible every 1/2 second, once the div is no longer visible, execute some code. In my example we show another div, but you could easily call a function or do whatever.
http://jsfiddle.net/vHmq6/1/
Script
$(function() {
setTimeout(function() {
$("#hideThis").hide();
}, 3000);
pollVisibility();
function pollVisibility() {
if (!$("#hideThis").is(":visible")) {
// call a function here, or do whatever now that the div is not visible
$("#thenShowThis").show();
} else {
setTimeout(pollVisibility, 500);
}
}
}
Html
<div id='hideThis' style="display:block">
The other thing happens when this is no longer visible in about 3s</div>
<div id='thenShowThis' style="display:none">Hi There</div>
If your code is running in a modern browser you could always use the MutationObserver object and fallback on polling with setInterval or setTimeout when it's not supported.
There seems to be a polyfill as well, however I have never tried it and it's the first time I have a look at the project.
FIDDLE
var div = document.getElementById('test'),
divDisplay = div.style.display,
observer = new MutationObserver(function () {
var currentDisplay = div.style.display;
if (divDisplay !== currentDisplay) {
console.log('new display is ' + (divDisplay = currentDisplay));
}
});
//observe changes
observer.observe(div, { attributes: true });
div.style.display = 'none';
setTimeout(function () {
div.style.display = 'block';
}, 500);
However an even better alternative in my opinion would be to add an interceptor to third-party function that's hiding the div, if possible.
E.g
var hideImportantElement = function () {
//hide logic
};
//intercept
hideImportantElement = (function (fn) {
return function () {
fn.apply(this, arguments);
console.log('element was hidden');
};
})(hideImportantElement);
I used this approach to wait for an element to disappear so I can execute the other functions after that.
Let's say doTheRestOfTheStuff(parameters) function should only be called after the element with ID the_Element_ID disappears, we can use,
var existCondition = setInterval(function() {
if ($('#the_Element_ID').length <= 0) {
console.log("Exists!");
clearInterval(existCondition);
doTheRestOfTheStuff(parameters);
}
}, 100); // check every 100ms

Fade-out controls when there's no keyboard/mouse input

Based on this script I found on Stack Overflow, I tried adapting it to fade out an editor panel on a HTML page. Fading out works fine, but I'd like limit the fade-out from being triggered.
What I hope to accomplish is to prevent the fade-out whenever the mouse is over the editor panel (and child controls) or when there's keyboard activity in one of the input children.
var i = null;
// this part is working
$("#my-canvas").mousemove(function() {
clearTimeout(i);
$("#panel,#btn-panel-toggle,#fps").fadeIn(200);
var i = setTimeout('$("#panel,#btn-panel-toggle,#fps").fadeOut(800);', 3000);
})
// this part is not working
$("#panel").mouseover(function() {
clearTimeout(i);
})
For a live example, please check out this jsFiddle.
Two independent variables are needed here to indicate, whether the input#sc-url is focused and div#panel is hovered by mouse or not. Then you can handle the timer with these functions:
$(function () {
var t = null; //timer
var is_url_focused = false, is_panel_hovered = false;
var panel = $('#panel');
function hide_panel(){
if (t) {
clearTimeout(t);
}
t = setTimeout(function(){
if (is_url_focused || is_panel_hovered) {
return;
}
panel.stop().animate({
opacity:0
},800, function(){
panel.hide(); // == diplay:none
});
},2000);
}
function show_panel(){
panel.show().stop().animate({
opacity:1
},800);
}
$('#my-canvas').mouseenter(function(){
show_panel();
}).mouseleave(function(){
hide_panel();
});
$('#panel').hover(function(){
is_panel_hovered = true;
show_panel();
}, function(){
is_panel_hovered = false;
hide_panel();
});
$('#sc-url').focus(function(){
is_url_focused = true;
show_panel();
}).blur(function(){
is_url_focused = false;
hide_panel();
});
$('#btn-panel-toggle').click(function(){
if (panel.is(':hidden')) {
panel.css('opacity',1).show();
} else {
panel.css('opacity',0).hide();
}
});
});
http://jsfiddle.net/w9dv4/3/

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;
});
})

Categories

Resources