I want to detect if is not visible in browser window for an interactive map i am building. if the div is not visible I will show a popup saying "this way" or something like that. The main issue is detecting when the div is not visible in the document window.
What I gather from your question is you want to detect if a div can be seen on the visible portion of the screen, NOT whether it's visible based upon its CSS (display, visibility).
If so, you need to determine the div's offset, then check if that's within the bounds of either the document dimensions, or another element's dimensions.
Something like this (assuming you're using jQuery)...
var div_offset = $('#div').offset();
if( div_offset.top < $(document).height() &&
div_offset.left < $(document).width() ) {
// div is within window bounds
}
This is a very basic example. You would of course need to factor in how much of the div element you would want to showing for it to be considered "visible"... the above code would be true even if only the single top/left pixel of the div sits within the document bounds. Do this by perhaps testing if the bottom right corner is showing by adding the width/height to the offset.
You can check as follows:
if (document.getElementById("myDiv").style.visibility == 'hidden'){
//
}else{
//
}
you can also use like this without "is"
// check if div is visible
$("div:visible").click(function () {
alert("hello to all");
});
// check if div is hidden
$("div:hidden").show("fast");
You can use is function with :visible
Live Demo
if($('#divId').is(':visible'))
{
alert("div is visible");
}
else
{
alert("div is not visible");
}
or
if($('#divId :visible').length)
{
alert("div is visible");
}
else
{
alert("div is not visible");
}
If you want to check if the element is visible in viewport you can use InView
Install it with npm :
npm install #opuu/inview
Use it like this :
// import it
import InView from "#opuu/inview";
// select elements to track
let elements = new InView(".selector");
// add enter event listener
elements.on("enter", (event) => {
console.log(event);
// do something on enter
});
// add exit event listener
elements.on("exit", (event) => {
console.log(event);
// do something on exit
});
Note: I wrote this package.
Related
Now, I want to make fade from top effect when my element be in the viewport by adding 'activate' class for it...
I don't want to use any external libraries that do it direct.
My code is:
window.addEventListener('scroll', function(e) {
var cards = document.querySelectorAll('cards');
for ( let card of cards ) {
if(!card.classList.contains('fadeFromTop')) {
card.classList.add('fadeFromTop');
}
}
}
but when my element goes out from the viewport, it still checks if the element has that class
I didn't add the if statement that checks if the element is inside the viewport.
Is there a way to break and stop the scroll event when all cards have the class 'fadeFromTop' ?
I tried to search on google but what I find is the element.removeEventListener(); and I can't understand what does it do...
I have a responsive design with multiple breakpoints. Some of the block dimensions in the content are calculated with jQuery. When the viewport changes these dimensions change thus the calculation should be run. How can I fire these events when the dimension of the reference element changes? The reference element changes when a breakpoint is crossed.
I've looked at the "orientationchange" event but it's not having the results I need.
You provide very little specifics and no code so all we can do is answer very generally.
Usually, you install a .resize() event handler and on every resize of the containing window, you check to see if the resulting dimensions have changed such that you need to recalculate and modify the layout.
$(window).resize(function(e) {
// check dimensions here to decide if layout needs to be adjusted
});
jQuery mobile supports the orientationchange event like this which also gives you e.orientation as "portrait" or "landscape":
$(window).on( "orientationchange", function(e) {
// check dimensions here to decide if layout needs to be adjusted
});
There are no DOM events for watching a size change on a specific element in the page other than a window object. Instead, you have to watch whatever other events might cause a given element to get resized which might be a resize of the window, an orientation change or some other action in the page that modifies the page (a button press or click on something, for example). Then, when those other events fire and get processed, you can then check the size of your target element and see if it changed.
Here's a jQuery plugin that debounces the resize event so it only tells you about a resize when the size has stopped changing:
(function($) {
var uniqueCntr = 0;
$.fn.resized = function (waitTime, fn) {
if (typeof waitTime === "function") {
fn = waitTime;
waitTime = 250;
}
var tag = "resizeTimer" + uniqueCntr++;
this.resize(function () {
var self = $(this);
var timer = self.data(tag);
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
self.removeData(tag);
fn.call(self[0]);
}, waitTime);
self.data(tag, timer);
});
}
})(jQuery);
Working demo: https://jsfiddle.net/jfriend00/k415qunp/
Sample usage:
$(window).resized(function() {
// put code here to act when window stopped getting resized
});
This page might help you. They talk about JS execution based on breakpoints and doing it with cross-browser support. Basically you'll be using a hidden pseudo element using the "content" property of .myClass:after.
I've got this code that goes through all my internal hrefs but I can't see to be able to figure out how to create an exception for one of the links that links to the div #section1. I need some kind of if statement surrounding the section.addClass("active"); line but I don't know which conditions to use to achieve this. Can you help?
Code: http://jsfiddle.net/vD3vP/
if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
//remove all selected elements
sections.removeClass("active");
//add current selected element.
section.addClass("active");
}
Like this:
$('a[href^="#"]:not(#exception)').click(function (event) {
//do stuff
});
Fiddle: http://jsfiddle.net/KyleMuir/vD3vP/1/
EDIT: You can determine whether or not it is the exception like this:
//Smooth scroll when user click link that starts with #
$('a[href^="#"]').click(function (event) {
if (!$(this).is('#exception')) {
alert('Hi');
}
//prevent the browser from jumping down to section.
event.preventDefault();
});
Fiddle: http://jsfiddle.net/KyleMuir/vD3vP/2/
Unless I misunderstood your question, you might add
$('a[href^="#section1"]').removeClass("active");
after section.addClass("active"); in the for loop inside checkSectionSelected().
You can do even better if you don't update the DOM tree unnecessarily using:
section.not('[href^="#section1"]').addClass("active");
Test here: http://jsfiddle.net/bcH3S/2/
Andrei
How can i create an action for an element which will change when the user is not over it. mouseover and mouseleave can't be applied in this situation because the element is activated on page load and the mouse location can be outside the element.
Here is the condition:
if mouse is not over element:
close element
else:
do nothing
So what i want to know is how can i check with jQuery/JavaScript if the current mouse position is not on the specific element.
Thanks!!
You could bind the event handler to the body and check for the requested target:
$().ready(function() {
$("body").on('mouseover',function(event) {
if($(event.target).attr('id') === 'yourid' ) {
console.log('do close this element');
} else {
console.log('do nothing');
}
});
});
I would use a global boolean to keep track of whether the mouse is currently hovering over the element or not. Then, you can periodically check that boolean using setInterval (with some reasonable time interval) which will decide whether the element should be hidden or not.
var mouseIsOver = false;
$('#elementId').hover(
function () {
mouseIsOver = true;
},
function () {
mouseIsOver = false;
}
);
setInterval(function() {
if (mouseIsOver == false) {
$('#elementId').fadeOut();
}
}, 250);
There is a brilliant jQuery plugin for just this. It's called jQuery outside events.
Check the homepage here: http://benalman.com/code/projects/jquery-outside-events/docs/files/jquery-ba-outside-events-js.html
The usage is super-simple and straight forward. I'd recommend this with great experience earlier.
I have the following scenario: On a label's mouseover event, I display a div. The div must stay open in order to make selections within the div. On the label's mouseout event, the div must dissappear. The problem is that when my cursor moves from the label to the div, the label's mouseout event is fired, which closes the div before I can get there. I have a global boolean variable called canClose which I set to true or false depending on the case in which it must be closed or kept open. I have removed the functionality to close the div on the label's mouseout event for this purpose.
Below is some example code.
EDIT
I have found a workaround to my problem, event though Alex has also supplied a workable solution.
I added a mouseleave event on the label as well, with a setTimeout function which will execute in 1.5 seconds. This time will give the user enough time to hover over the open div, which will set canClose to false again.
$("#label").live("mouseover", function () {
FRAMEWORK.RenderPopupCalendar();
});
$("#label").live("mouseout", function () {
setTimeout(function(){
if(canClose){
FRAMEWORK.RemovePopupCalendar();
}
},1500);
});
this.RenderPopupCalendar = function () {
FRAMEWORK.RenderCalendarEvents();
}
};
this.RenderCalendarEvents = function () {
$(".popupCalendar").mouseenter(function () {
canClose = false;
});
$(".popupCalendar").mouseleave(function () {
canClose = true;
FRAMEWORK.RemovePopupCalendar();
});
}
this.RemovePopupCalendar = function () {
if (canClose) {
if ($(".popupCalendar").is(":visible")) {
$(".popupCalendar").remove();
}
}
};
Any help please?
I would wrap the <label> and <div> in a containing <div> then do all you mouse/hide events on that.
Check out this fiddle example - http://jsfiddle.net/6MMW6/1
Give your popupCalendar an explicit ID instead of a class selector, e.g.
<div id="popupCalendar">
Reference it with #popupCalendar instead of .popupCalendar.
Now, remove() is quite drastic as it will completely remove the div from the DOM. If you wish to display the calendar again you should just .hide() it.
But your logic seems a bit overly complex, why not just .show() it on mouseenter and .hide() on mouseout events ?
This will close the entire tab page if the tab page loses focus.
How ever if you target it, it can work for something within the page too, just change the target codes.
JavaScript:
<script type="text/javascript" >
delay=1000 // 1 sec = 1000.
closing=""
function closeme(){
closing=setTimeout("self.close()",delay)
// self means the tab page close when losing focus, but you can change and target it too.
}
<!--// add onBlur="closeme()" onfocus="clearTimeout(closing)" to the opening BODY tag//-->
</script>
HTML:
<body onBlur="closeme()" onfocus="clearTimeout(closing)">