How to disable the <a> link and resume it after? - javascript

I have a page that is similar to http://tv.sky.com/tv-guide/#/day/0.
I used "DragScroll" to make the program area work, and it works.
But here's the problem, I need to prevent the a for keep getting clicked after the drag. So I tried using preventDefault(), and actually it works! but how do I resume the link back so the user can click on it if they weren't dragging? What's could be the event for it?

You can try to use this code:
var down = false;
var drag = false;
$('...').mousedown(function() {
down = true;
}).mouseup(function() {
down = drag = false;
}).mousemove(function() {
if (down) {
drag = true;
}
}).on('click', 'a', function(e) {
if (drag) {
e.preventDefault();
}
});

used something similar to setTimeout instead.
var golocation = function() {
var href = $(this)[0].dataset.href;
window.location = href;
}
var start_time;
$('a')
.on('mousedown', function(e) {
start_time = new Date().getTime();
})
.on('mouseup', function(e) {
var now = new Date().getTime();
if (now - start_time < 100) {
golocation.call(this);
};
});

Related

Click event works on third or fourth try on button

This is a continuation of This
I used setTimeout() to place cursor on the input fields on pressing the tab, without which the focus goes to a link outside the <div> for some reason I am not aware of.
setTimeout() fixed that issue, but now:
On clicking on submit button the form does nothing but place cursor on the input fields for three or four times then proceeds with submitting.
Here is the submit button functions
$(“#submitbtn”).click(function(e) {
console.log(“click”);
e.preventDefault();
var s = setTimeout(function() {
removeTimeouts();
startValidation();
});
e.stopPropagation();
e.cancelBubble = true;
});
Here is hover function for Submit button
$(“#submitbtn”).mouseover(function(e) {
console.log(“Hover”);
removeTimeouts();
$(“#submitbtn”).focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
The function removeTimeouts() has all clearTimeout() for all setTimeout() through out the JavaScript file.
But somehow the click function is never works until third or fourth try.
The hover function works on first mouse move though, it prints “Hover” on console, every time the mouse it moves over submit button.
Even after clearing all setTimeout() somehow the focus is moved to input fields instead of proceeding with the console.log() onclick.
Can someone help me understand the issue and help fix the form gets submitted on first click?
Update:
1) This is typed from mobile app, even after re-editing the quote appearing as “” It’s correct in my code just not here.
2) Focus and timeout event is to validate the input fields while moving out of the input field, like if the field is empty, the cursor won’t move to next input field. But just focus is not working, and tab just takes the cursor out of the input fields to a link below it, so time-out helps keeping the cursor the input field.
3) Snippet - This does not replicate the issue as this is by far I can post the code sorry :(
(function ($) {
// Behind the scenes method deals with browser
// idiosyncrasies and such
$.caretTo = function (el, index) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move("character", index);
range.select();
} else if (el.selectionStart != null) {
el.focus();
el.setSelectionRange(index, index);
}
};
// Another behind the scenes that collects the
// current caret position for an element
// TODO: Get working with Opera
$.caretPos = function (el) {
if ("selection" in document) {
var range = el.createTextRange();
try {
range.setEndPoint("EndToStart", document.selection.createRange());
} catch (e) {
// Catch IE failure here, return 0 like
// other browsers
return 0;
}
return range.text.length;
} else if (el.selectionStart != null) {
return el.selectionStart;
}
};
// The following methods are queued under fx for more
// flexibility when combining with $.fn.delay() and
// jQuery effects.
// Set caret to a particular index
$.fn.caret = function (index, offset) {
if (typeof(index) === "undefined") {
return $.caretPos(this.get(0));
}
return this.queue(function (next) {
if (isNaN(index)) {
var i = $(this).val().indexOf(index);
if (offset === true) {
i += index.length;
} else if (typeof(offset) !== "undefined") {
i += offset;
}
$.caretTo(this, i);
} else {
$.caretTo(this, index);
}
next();
});
};
// Set caret to beginning of an element
$.fn.caretToStart = function () {
return this.caret(0);
};
// Set caret to the end of an element
$.fn.caretToEnd = function () {
return this.queue(function (next) {
$.caretTo(this, $(this).val().length);
next();
});
};
}(jQuery));
var allTimeouts = [];
function placeCursor(id) {
id.focus(function(e) {
e.stopPropagation();
//e.cancelBubble();
id.caretToEnd();
});
id.focus();
}
function removeTimeouts(){
for(var i = 0; i < allTimeouts.length; i++) {
clearTimeout(allTimeouts[i]);
}
}
function focusInNumber (id) {
var thisID = id;
var nextID = id + 1;
var preID = id - 1;
//$("#number" + thisID).prop("disabled", false);
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
});
allTimeouts.push(s);
if(preID != 0) {
if($("#number" + preID).val().length <= 0) {
var s = setTimeout(function() {
placeCursor($("#number" + preID));
});
allTimeouts.push(s);
}
}
}
function focusOutNumber (id) {
var thisID = id;
var nextID = id + 1;
var preID = id - 1;
var value = $("#number" + thisID).val();
var regex = new RegExp(/^\d*$/);
var regex1 = new RegExp(/^.*[\+\-\.].*/);
var l = $("#number" + thisID).val().length;
if(!value.match(regex)) {
alert("Just enter numerical digits");
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
},5000);
allTimeouts.push(s);
} else {
if (l<=0) {
alert("This field cannot be empty");
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
},5000);
allTimeouts.push(s);
} else {
if(value.match(regex)) {
var s = setTimeout(function() {
placeCursor($("#number" + nextID));
}, 100);
allTimeouts.push(s);
}
}
}
}
$(document).ready(function(){
$("#number1").focusin(function(){
focusInNumber(1);
});
$("#number1").focusout(function(){
focusOutNumber(1);
});
$("#number2").focusin(function(){
focusInNumber(2);
});
$("#number2").focusout(function(){
focusOutNumber(2);
});
$("#number3").focusin(function(){
focusInNumber(3);
});
$("#number3").focusout(function(){
focusOutNumber(3);
});
$("#number4").focusin(function(){
focusInNumber(4);
});
$("#number4").focusout(function(){
focusOutNumber(4);
});
$("#submitbtn").click(function(e) {
console.log("click");
e.preventDefault();
var s = setTimeout(function() {
removeTimeouts();
alert("startValidation()");
});
e.stopPropagation();
e.cancelBubble = true;
});
$("#submitbtn").mouseover(function(e) {
console.log("Hover");
removeTimeouts();
$("#submitbtn").focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
});
.SubmitBtn {
width: 100%;
background-color: #cccccc;
}
.Submitbtn:hover {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="reqField" id="number1" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number2" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number3" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number4" placeholder="Enter Number only"></input>
<div id="submitbtn" class="SubmitBtn">Submit</div>
After breaking my head and console.log on all the statement to figure out the flow of code, I was able to find that on $("#submitbtn").click() there is some .focusout() is called.
As these .focusout() were necessary for on the go validation on the <input> fields, i tried to add $.(":focus").blur() and it worked along with adding a return false; on placeCursor() function.
The $.(":focus").blur() removes focus from any currently focused element. And this is a live saver for our logic of code.
So the code looks like
$("#submitbtn").mouseover(function(e) {
console.log("Hover");
$.(":focus").blur();
removeTimeouts();
$("#submitbtn").focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
....
function placeCursor(id) {
id.focus(function(e) {
e.stopPropagation();
//e.cancelBubble();
id.caretToEnd();
});
id.focus();
return false;
}
Hope this helps someone someday.
Thank you!

how to stop executting eventlisteners

Hi I've got some issues with my small project. I want to stop executting the mousedown and mousemove event after the mouseup event invokes. But after that the mousedown event must be active again. It should work like a reset. Here is the code
function quotesMouseDown(event) {
var isMouseDown = true;
document.getElementById("quotes").addEventListener("mouseup",
function() {
isMouseDown = false;
});
if (isMouseDown == false) {
return false;
}
else {
var mDownX = event.pageX;
document.getElementById("quotes").addEventListener("mousemove", quotoesMouseMove);
function quotoesMouseMove(event) {
var mMoveX = event.pageX;
console.log(mMoveX);
console.log(mDownX + "cos")
}
}
console.log(isMouseDown);
}
document.getElementById("quotes").addEventListener("mousedown", quotesMouseDown);
Just detach the mousedown callback at the end of the mouseup callback:
document.getElementById("quotes").addEventListener("mouseup", function() {
isMouseDown = false;
document.getElementById("quotes").removeEventListener("mousedown", quotesMouseDown);
});

How can I change style of element with jQuery function and media query when resize event working

I'm making a responsive web site, and I have some problems at resize.
I using media query at ww<1280, ww<1024, ww<640, then controll elements with Jquery Functions.
when document loaded, media query and functions are worked well.
but, when I try some jquery functions then resize window, there are so many problems.
one of function I wrote is,
var menuOpen = function() {
var ctryBtn = $(".countryMenu input[type=button]");
var ctryMenu = $(".countryMenu");
var subGnb = $("#subGnb");
var gnbBtn = $("#header button.mobileGnbBtn");
var myGnb = $("#gnb");
var schBtn = $(".mobileFindBtn");
var schMenu = $(".utilMenu");
var gnbDown = function () {
$("#gnb ul").append("<li class='mobileSiteMap'><a href='siteMap.html'>Site Map</a></li>");
myGnb.slideDown(500,function () {
$(".mobileGnbBtn").css({
"width":"37px",
"height":"37px",
"background-image":"url(image/common/btn-close-mobile.png)",
"background-size":"cover"
});
});
};
var gnbUp = function () {
if ($(window).width() <= 623) {
myGnb.slideUp(500, function () {
$(".mobileSiteMap").remove();
$(".mobileGnbBtn").css({
"width":"43px",
"height":"37px",
"background-image":"url(image/common/btn-menu-mobile.png)"
});
});
} else {
$(".mobileSiteMap").remove();
return false;
}
};
ctryBtn.on("click", function () {
if(isSubGNB === false){
subGnb.slideDown(500);
isSubGNB = true;
} else {
subGnb.slideUp(500);
isSubGNB = false;
}
});
gnbBtn.on("click", function () {
if(isGNB === false){
if(isSubGNB === true || isSearch === true){
subGnb.slideUp(500);
isSubGNB = false;
schMenu.slideUp(500);
isSearch = false;
ctryMenu.fadeIn(300);
}
gnbDown();
isGNB = true;
} else {
gnbUp();
isGNB = false;
}
});
schBtn.on("click", function () {
if (isSearch === false) {
if (isGNB === true || isSubGNB === true ) {
gnbUp();
isGNB = false;
subGnb.slideUp(500);
isSubGNB = false;
}
ctryMenu.fadeOut(100);
schMenu.slideDown(300);
isSearch = true;
} else {
schMenu.slideUp(100);
isSearch = false;
ctryMenu.fadeIn(300);
}
});
};
#gnb is absolute positioned at ww<640, invisible(display:none), and different children elements setting with another ww sizes.
#gnb is relative positioned at upper 640px ww.
Then I wrote resize event like:
$(window).on("resize", function () {
var gnbPC = function () {
$("#gnb").css({
"width":"410px",
"height":"76px",
"letter-spacing":"-0.04em",
"margin-left":"26.866%"
});
};
var toggleMobile = function () {
if ($(window).width() <= 623 ) {
$("#subGnb").css({"display":"none"});
} else {
gnbPC();
$("#subGnb").css({"display":"none"});
}
};
clearTimeout(timer);
timer = setTimeout(toggleMobile, delta);
});
I set var delta = null; var timer = null;
Under 640px ww, when I click button, #gnb slideDown, and slideUp well.
when #gnb slideUp, then I try resize to upper 640px,
there is no #gnb because it had invisibled when slideUp() finished.
So I try to give it CSS set(default value of CSS ww>640),
but it is written inline, then mediaQuery didn't work.
I want some solution, when I trying resize window,
function work then reload for default setting for ww size.
Or, solve this resizing problems.
I want reset when resize,
if #gnb opened, then I try resize, I want it closed then change to default setting for ww size.

Detect multiple keypresses on Firefox (Greasemonkey)

So I'm trying to be able to trigger a script using a combinations of keypresses.
var down = {
};
$(document).chardown(function (e) {
down[e.charCode] = true;
}).charup(function (e) {
if (down[68] && down[69] && down[86]) {
var nextButton = document.getElementsByClassName('button-next') [0];
nextButton.click();
}
down[e.keyCode] = false;
});
This is the code I've got so far. So the intention is (afaik) to trigger the
var nextButton = document.getElementsByClassName('button-next') [0];
nextButton.click();
When I press e+d+v. But it isn't working. And if I only use the above part it keeps changing episode (Obvioulsy).
I didn't find any documentation related to chardown and charup in jquery or greasemonkey.I think you were trying to use keydown and keup. You should replace charCode with keyCode.
var down = {};
$(document).keydown(function (e) {
down[e.keyCode] = true;
}).keyup(function (e) {
if (down[68] && down[69] && down[86]) {
alert("Hello");
}
down[e.keyCode] = false;
});

Setinterval with exponential time decrease

I've got a mousedown event with a setinterval. I want the time of intervals to be variable. So the first one is 500, the second one 500/2 = 250, etc. Any tips?
$plus.mousedown(function(e) {
increment(20)
timeout = setInterval(function(){
increment(20)
}, 500);
});
$(document).mouseup(function(){
clearInterval(timeout);
return false;
});
Cheers!
EDIT: sorry for the ambiguity. I want the time of interval to change during the mousedown. So while the mousedown is being performed the intervaltime should change. So not by every single mouse click but with every continuous click, and then reset it again.
You can't really do this with setInterval() unless you keep clearing for a delay change, so you might as well write a wrapper around setTimeout() to accomplish something similar:
function easingTimeout(delay, fn)
{
var id,
invoker = function() {
fn();
delay = Math.floor(delay / 2);
if (delay) {
id = setTimeout(invoker, delay);
} else {
id = null;
}
}
// start it off
id = setTimeout(invoker, delay);
return {
clear: function() {
if (id) {
clearTimeout(id);
id = null;
}
}
}
To use:
var timeout;
$plus.mousedown(function(e) {
increment(20);
timeout = easingTimeout(500, function() {
increment(20);
});
});
$(document).mouseup(function(){
timeout.clear();
return false;
});
This solution does not depend on jQuery:
var timeoutInterval = 500;
var mousedown = false;
function incrementAndWait() {
if (!mousedown) return;
increment(20);
timeout = setTimeout(incrementAndWait, timeoutInterval);
timeoutInterval /= 2;
}
document.onmousedown = function() {
timeoutInterval = 500; // Reset to 500 to allow multiple mousedown/mouseup
mousedown = true;
incrementAndWait();
};
document.onmouseup = function() {
mousedown = false;
}
You can add console.log((new Date).getTime(), 20); to the incrementAndWait method to see the numbers going on the console. Something fun to play with :)

Categories

Resources