Modal Popup on Window exit - resets one time - javascript

I would like to use only one time modal when a user leaves on the Window.
$(document).mousemove(function(e) {
if (e.clientY <= 1) {
//Modal
}
});
Let me know how can I create it.

Assuming that you already have the modal element created in your HTML then I think this should do what you want...
$(document).mousemove(function(e) {
if (e.clientY <= 1 && modalShown != 1) {
modalShown = 1;
$('#myModal').modal('show');
}
});

Related

Keyboard disappearing when input on focus - mobile

I have this code and everything works good, but when I open my search bar on mobile and click on input field, my keyboard opens and closes, I found that window.resize is the problem, but I haven't found any fixes for this, what should I do?
function appendSearchBar() {
if($(window).width() <= 769){
$('.search-bar').appendTo('.mobile-toolbar .global-search');
} else {
$('.search-bar').appendTo('.header-toolbar-nav .global-search');
}
}
$(window).resize(function() {
appendSearchBar();
});
When you appendTo the element is detach and re-attached to the DOM and thus loses focus.
You should only append if it is not where you want it.
let inMobile;
function appendSearchBar(firstTime) {
const windowWidth = $(window).width();
if (windowWidth <= 769 && (!inMobile || firstTime)) {
inMobile = true;
$('.search-bar').appendTo('.mobile-toolbar .global-search');
}
if (windowWidth > 769 && (inMobile || firstTime)) {
inMobile = false;
$('.search-bar').appendTo('.header-toolbar-nav .global-search');
}
$(window).resize(function() {
appendSearchBar();
});
appendSearchBar(true);

dblclick function is not same as tap function on touch device [duplicate]

I have the following jquery event handling function:
$('.target').on('dblclick', function() {
//respond to double click event
});
My issue is that this event handler doesn't work on touch devices (iPhone, iPad...). Can anyone recommend a reliable alternative to dblclick that works on touch devices and still allows comfortable double click use on full size devices?
I ended up building a custom double click function that will work on both mobile and desktop:
var touchtime = 0;
$(".target").on("click", function() {
if (touchtime == 0) {
// set first click
touchtime = new Date().getTime();
} else {
// compare first click to this click and see if they occurred within double click threshold
if (((new Date().getTime()) - touchtime) < 800) {
// double click occurred
alert("double clicked");
touchtime = 0;
} else {
// not a double click so set as a new first click
touchtime = new Date().getTime();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="target">Double click me</div>
Alternatively, here is the JSfiddle Demo.
Add this to your index.html
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
I found the mobile zoom function would throw off Jquery's dblclick. Basically it says your viewport wont change effectively shutting off the zoom. This works for me on my Nexus 5 running Chrome.
I know the question has been answered but thought it would be worth putting the solution I use all the time, cheers:
var doubleClicked = false;
$('.target').on('click', function() {
if (doubleClicked) {
//do what you want to do on double click here
}
doubleClicked = true;
setTimeout(() => {
doubleClicked = false;
}, 300);
});
You can bind multiple event listeners on the element and use jQuery's tap event for the touch devices.
$( ".target" ).on({
dbclick: function() {
//do stuff
}, touch: function() {
//do the same stuff
}
});
Thanks for the solution - the only thing I did was add a timeout so that they could be treated as separate events
var touchtime = 0;
var delay = 800;
var action = null;
$(".target").on("click", function() {
/*Double Click */
if((new Date().getTime() - touchtime) < delay){
clearTimeout(action)
alert('dbl');
touchtime=0;
}
/* Single Click */
else{
touchtime = new Date().getTime();
action = setTimeout(function(){
alert('single');
},delay);
}
}));
Although I haven't tested it, might also be worth adding the following to a header section of any HTML <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/> as per: To "user-scalable=no" or not to "user-scalable=no"
The marked answer of #JRulle seems to work only for a single object, if u have many instances with the same class they will be considered as a single object
see the exampleFiddle example
My solution seems to work in cases like that
var touchtime = 0;
$('.target').on('click', function() {
if (touchtime == 0) {
touchtime = new Date().getTime();
} else {
if (((new Date().getTime()) - touchtime) < 800) {
alert("double clicked");
touchtime = 0;
} else {
touchtime = 0;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p class="target">click me!</p>
<p class="target">then click me!</p>
click link
Multiple targets with own doubleclick counter. The accepted solution has 2 bugs, that are fixed here:
If you click on target and click outside and click on target again within 800 ms, then the doubleclick event fires.
If you have multiple targets, click on different targets within 800 ms, and the doubleclick event fires.
$(document).on("click", function(e)
{
var MAX_DELAY_IN_MS = 800;
var current_time = new Date();
var targets = $(".target");
if ((typeof last_target == "undefined") ||
(last_target == 0))
{
last_target = e.target;
last_click = current_time;
}
else
{
if ((last_target == e.target) &&
((targets.is(e.target) == true) ||
(targets.has(e.target).length !== 0)) &&
(current_time - last_click < MAX_DELAY_IN_MS))
{
alert("double clicked");
}
last_target = 0;
last_click = 0;
}
});
div{display:inline-block; width:30px; height:30px; margin:5px;}
.target{background-color:lime;}
.no_target{background-color:orange;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="target"></div>
<div class="target"></div>
<div class="no_target"></div>
<div class="target"></div>
Programmatically all of the answers given above are fine.
When you double click on mouse button it's just the mass off your finger involved,
so it can be fast...
On the other hand when tapping touch screen usually much larger physical mass is involved.
Larger mass means slower times .
So my approach is "click two times" instead of double click.
Means a global variable e.g var ClickCounter=0;
Inside the function scope
ClickCounter++;
Check if ClickCounter ==2.
Execute your Code.
Reset counter ClickCounter=0
else return false or execute another code
I have an improvement to the code above, that didnĀ“t detect a doubleclick after a single click:
var touchtime = 0;
$(".target").on("click", function() {
if (((new Date().getTime()) - touchtime) < 500) {
alert("double clicked");
}
touchtime = new Date().getTime();
});
This code detects all doubleclicks. I also reduced the touchtime to 500ms (standard doubleclick-time).
The only way is to detect double touch yourselves. You can do it by persisting last touch event timestamp like below:
if (e.touches.length === 1) {
if (this.lastTouchEventTimeStamp) {
const timeInMillisecondsSinceLastTouch = e.timeStamp - this.lastTouchEventTimeStamp;
if (timeInMillisecondsSinceLastTouch > 80 && timeInMillisecondsSinceLastTouch < 400) {
// double tap will be detected here
this.lastTouchEventTimeStamp = undefined;
const dblClickEvent = new DragEvent('dblclick', {
view: window,
bubbles: true,
cancelable: true
});
e.target.dispatchEvent(dblClickEvent);
}
}
this.lastTouchEventTimeStamp = e.timeStamp;
}
Came across this thread and wanted to supply an updated answer.
function doubleClick(event, callback) {
var touchtime = $(event.target).data("touch-time");
if (touchtime == undefined || touchtime == 0) {
// set first click
$(event.target).data("touch-time", new Date().getTime());
} else {
// compare first click to this click and see if they occurred within double click threshold
if (((new Date().getTime()) - touchtime) < 800) {
// double click occurred
callback();
$(event.target).data("touch-time", 0);
} else {
// not a double click so set as a new first click
$(event.target).data("touch-time", new Date().getTime());
}
}
}
It can then be used as follows:
$(selector).click(function(event){
doubleClick(event, function(){
console.log("Hello World");
});
});
This uses the Data Attribute versus a global variable to get/set the Touch Time.
The standard dblclick should work in modern mobile browsers.
This is it... in CoffeeScript
onDblClick = -> "...your function to be fired..."
dbl_click = null
$(element).on 'mousedown', ->
onDblClick() if dbl_click
dbl_click = true
setTimeout () ->
dbl_click = false
, 250
You need to enter "return false" to the end of the function like below
var touchtime = 0;
$('.dbclickopen').click(function() {
if(touchtime == 0) {
//set first click
touchtime = new Date().getTime();
} else {
//compare first click to this click and see if they occurred within double click threshold
if(((new Date().getTime())-touchtime) < 800) {
//double click occurred
touchtime = 0;
window.location = this.href;
} else {
//not a double click so set as a new first click
touchtime = new Date().getTime();
}
}
return false;
});

Detecting click on window scrollbar

I'm trying to pause the main window scroll when scrolling a table, which I've done but are having trouble enabling the main window scroll again after.
This function will pause the main window scroll when scrolling over table.
function preventWindowScroll() {
scrollTable = document.querySelector(".members-data");
if (scrollTable.contains(event.target)) {
var oldScrollPos = document.body.scrollTop;
window.onscroll = function () { window.scrollTo(0, oldScrollPos); };
} else {
// disable scrollTo in order to reenable main window pause
window.onscroll = function () {};
}
}
The problem is that if I try to scroll down by clicking and dragging the main window scrollbar it's still jammed by scrollTo.
I've tried doing an onclick event, but it doesn't work when clicking scrollbar.
document.body.onclick = function(e) {
scrollTable = document.querySelector(".members-data");
if (!scrollTable.contains(e.target)) {
window.onscroll = function () {};
}
};
I've also tried removing the event listener, but can't figure out where to put it.
document.body.removeEventListener('mousewheel', preventWindowScroll);
document.body.removeEventListener('DOMMouseScroll', preventWindowScroll);
If I could just detect when a user clicks on the main window scroll eit would work as intended.
note: I have achieved pausing the main window scroll other ways, but they all have slight drawbacks.
Thanks
I use this code. Works in Chrome.
yourTable.addEventListener('wheel', handleMouseScroll);
function handleMouseScroll(e) {
var delta = e.deltaY || e.detail || e.wheelDelta;
if (delta < 0 && this.scrollTop == 0) {
e.preventDefault();
}
if (delta > 0 && this.scrollHeight - this.clientHeight - this.scrollTop <= 1) {
e.preventDefault();
}
}

Scroll position based javascript animation does not revert to it's original state when scrolling back up

See the JSFiddle here: http://jsfiddle.net/jL6d2qp6/
I have an animation that is supposed to keep the #top element in a fixed position at the top of the page, except for when the #login element is on the screen. To control this, I am using a javascript function that runs every 10ms and switches out the css class for #top, and when I scroll down, it updates as expected, but when I try to scroll back up, nothing happens.
javascript code in question:
offScreen = function(id, targetValue)
{
var offset = $("#top").offset();
var w = $(window);
var height = $(id).innerHeight();
var finalOffset = (offset.top + height) - w.scrollTop();
if (finalOffset < targetValue)
{
return true;
}
else
{
return false;
}
}
function updateTopMenu()
{
if (offScreen("#login", 81) === false)
{
if($("#top").hasClass("top-bar-absolute") === false)
{
$("#top").addClass("top-bar-absolute");
console.log("added top-bar-absolute");
}
if($("#top").hasClass("top-bar-fixed") === true)
{
$("#top").removeClass("top-bar-fixed");
console.log("removed top-bar-fixed");
}
}
if(offScreen("#login", 81) === true)
{
if($("#top").hasClass("top-bar-absolute") === true)
{
$("#top").removeClass("top-bar-absolute");
console.log("removed top-bar-absolute");
}
if($("#top").hasClass("top-bar-fixed") === false)
{
$("#top").addClass("top-bar-fixed");
console.log("added top-bar-fixed");
}
}
}
$("#top").ready( function() {
setInterval(updateTopMenu, 10);
});
Also, if there is a better way to accomplish this, I'd like it because this feels kind of cheaty.
The easiest way to achieve this is listening to the scroll event on the window. This is called every time the user scrolls. Then you can check whether the user scrolled past the login box, i.e. beyond the login box's height.
If the login box is no longer in the window, assign the #top box a class like .sticky that will change its position to position: fixed. And otherwise remove this class.
Checkout this jsFiddle.

Content Click Counter

I need to count the number of clicks on a piece of content - after which, I need to run a certain function.
I can't run the function on every click, only after the user finishes their desired clicks.
The amount of clicks needs to be 1, 2, or 3 and above, where I only want to do something on one or two clicks, and ignore anything else.
Note I only need to run the function after the clicks, then reset the counter.
I've tried the following, but it logs 'single' after every click.
var clicks = 0;
$(controller).click(function() {
var elem = this, $elem = jQuery(elem), clicks = $elem.data('clicks') || 0;
clicks += 1;
// Reset triple click counter if no click is made within 500ms
setTimeout(function() {
clicks = 0;
}, 500);
setTimeout(function() {
if (clicks >= 3) {
console.log("triple or more");
}
if (clicks === 2) {
console.log("double");
}
if (clicks === 1) {
console.log("single");
}
}, 200);
});
Here is a JSBin example
It's a little hard to see what you want to happen after 3 clicks, do you want to trigger triple clicks for each of them or not.
I created a version that you might want to look at: http://jsbin.com/dutilojujowa/5/edit
The ideas are:
Save all the click counter data into the data attribute instead of relying on scope - I find that easier.
Throttle your reset counter, otherwise multiple clicks can be handled very strangely
Throttle your action counter, or you might get multiple actions accidentally!
Make sure you set $elem.data('clicks') to 1 at some point, or it won't work.
You need to update $elem.data('clicks') at the end of your function. See http://css-tricks.com/snippets/jquery/triple-click-event/
Can you try following code:
var totalCount;
var intervalVar;
var ShowResultVar;
function HandleClicks() {
totalCount = totalCount + 1;
}
function ShowResult() {
if(totalCount == 0)
{
console.log("No Clicks");
}
else if (totalCount == 1)
{
console.log("One Click");
}
else if(totalCount == 2)
{
console.log("Two Clicks");
}
else if (totalCount >2) {
console.log("Three or more Clicks");
}
}
$(document).ready(function () {
totalCount = 0;
$("#myControl").bind("click", HandleClicks);
intervalVar = setInterval(function () {
totalCount = 0;
}, 500);
ShowResultVar = setInterval(function () {
ShowResult();
}, 200);
});
It is working for me. Output is as follows:
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
One Click
Two Clicks
One Click
Two Clicks
No Clicks
One Click
Two Clicks
No Clicks
One Click
Two Clicks
Two Clicks
Three or more Clicks
One Click
One Click
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
Try this-
$("#content").data('clicks', 0);
$("#content").click(function () {
var elem = this,
$elem = jQuery(elem);
var clicks = $elem.data('clicks') + 1
$elem.data('clicks', clicks);
if (clicks == 1) {//start re-setter and counter when first click
setTimeout(function () {
$elem.data('clicks', 0);
}, 500);
setTimeout(function () {
var clicks = $elem.data('clicks');
if (clicks >= 3) {
console.log("triple or more");
}
if (clicks === 2) {
console.log("double");
}
if (clicks === 1) {
console.log("single");
}
}, 200);
}
});
DEMO

Categories

Resources