How to disable opening new browser tab by Ctrl + click - javascript

Good day.
I have a list of some products. I realized multiple select products using Ctrl key.
$(parentSelector).on("click", function (evnt) {
evnt.stopImmediatePropagation();
var item = $(evnt.delegateTarget)
// TODO: clarify how to rewrite event handling
if (!evnt.ctrlKey && !evnt.metaKey) {
var selectedItems = $("#tabs .popup-body").find("a.item.selected");
$.each(selectedItems, function () {
$(this).removeClass("selected");
});
} else {
if (item.hasClass("selected")) {
item.removeClass("selected")
} else {
item.addClass("selected")
}
return false;
}
});
In "else" block product becomes selected or not selected.
But while tab isn't loaded fully, Ctrl+click opens new tab, how to prevent it?
Thank you.

maybe you need something like this?
element.onclick = function(event) {
event.preventDefault();
//do stuff
};
Demo: http://jsbin.com/okoRorU/

Related

jQuery on click toggle event

I've made a function which selects an item when you click on it. And made it so when I've selected more than 10, it stops adding to selectedItems.
But when 10 items is selected, I can still toggle the class d-items-selected by clicking. How do I disable that? I've tried to use stop() but that canceled the hole thing, so I couldn't 'de-select' the items again.
$(document).ready(function(){
$('.d-items').on('click', function(e){
e.preventDefault();
$(this).toggleClass('d-items-selected');
var selectedItems = $('.d-items-selected').length;
if(selectedItems > 10) {
$('.d-items').finish();
} else {
$('#ItemsSelected').html(selectedItems);
}
});
});
You can disable controls which are not selected. Something like this.
$(document).ready(function(){
$('.d-items').on('click', function(e){
e.preventDefault();
$(this).toggleClass('d-items-selected');
var selectedItems = $('.d-items-selected').length;
if(selectedItems > 10) {
//do not allow to select
$(this).removeClass('d-items-selected');
} else {
$('#ItemsSelected').html(selectedItems);
}
});
});
Would unbinding the click event work for you?
e.g.
if(selectedItems > 10) {
$('.d-items').unbind("click");
}
Otherwise you can rebind it to a different function after selectedItems > 10, or anything really.
edit: It would help if you clarified what exactly you want to happen on click after selectedItems > 10
Maybe try
e.stopPropagation() or
e.stopImmediatePropagation()
I tried to figured out a solution:
$(function () {
$('.d-items').on('click', function(e) {
e.preventDefault();
var selectedItems = $('.d-items-selected').length;
//if selected items are less then 10
// or the current item is already selected you can deselect
if (selectedItems<10 || (selectedItems>=10 && $(this).is('.d-items-selected'))) {
$(this).toggleClass('d-items-selected');
}
if (selectedItems > 10) {
$('.d-items').finish();
} else {
$('#ItemsSelected').html(selectedItems);
}
});
});
$(document).ready(function(){
var i=0;
$('.d-items').on('click', function(e){
e.preventDefault();
if($(this).hasClass('d-items-selected')) {
$(this).removeClass('d-items-selected');
i--;
console.log("deleted"+i);
}
else {
if(i<10) {
$(this).addClass('d-items-selected');
i++;
console.log("added"+i);
}
}
})
});

call different events based on user input style javascript

I have a div which contains an input element to enter some values. These values are added just above the div as a list element upon pressing enter or onFocusOut event. To this point it is fine. But if user types some value and does not press enter and directly clicks on save button, the onFocusOut function for that div should not be called. Instead it should take that typed value and call some save function. Do you have any suggestion on how to detect it?
My code snippet is here
JS:
divInput.onkeypress = function (event){
return someTestFunc();
}
divInput.tabIndex="-1";
$(divInput).focusout(function (e) {
if ($(this).find(e.relatedTarget).length == 0) {
addToList();
}
});
It is not a very delicate solution, but you could use a setTimeout before adding the item to the list and clear the setTimeout on save.button click.
Try this:
var $saveButton = $('#exampleButton')[0],
$divInput = $('#exampleInput')[0],
timedEvent = -1;
$($saveButton).on('click', function(event){
if(timedEvent) {
clearTimeout(timedEvent)
}
alert('not add to list & save');
})
$divInput.tabIndex="-1";
$($divInput).on('focusout', function(e) {
timedEvent = window.setTimeout(function() {
if ($(this).find(e.relatedTarget).length == 0) {
alert('add to list');
}
}, 200);
});
Check this working fiddle

jQuery slideToggle menus based on mouseenter/leave

I've mostly got a little menu system working, but having a couple quirks I can't figure out. There don't seem to be any questions I can find with this same issue.
The functional example is at http://louisnk.com/photography - the only menu that has pretty much all the code in place is 'USA'.
on click, the menu shows, and I want it to:
A) delay, then slide back up if the mouseenter event never fires
B) not slide back up if the mouseenter event does fire
C) delay, then slide back up when the mouseleaves
I have it pretty well down, except I believe I have some event delegation issues...
The first time I click, it all works great. The second time I click on any menu, it seems like 'poked' (the variable which gets set as true/false depending on the switch case) is being set to false, and so automatically causing the 'noPoke' function to close the menu regardless of the mouseenter event. Subsequent clicks obviously cause stranger behavior.
I have the following code all wrapped in a document ready function:
var menuSwitch = function(menu) {
$(menu).on('mouseenter mouseleave', function(e) {
switch(e.type) {
case 'mouseenter':
poked = true;
console.log('probed');
return false;
break;
case 'mouseleave':
$(this).delay(1500).slideUp(500,function() {
$(menu + 'li').hide();
console.log('switched');
});
poked = false;
break;
default:
poked = false;
console.log('defaulting');
break;
}
});
}
var noPoke = function(menu) {
if (poked == false) {
$(menu).delay(2000).slideUp(500,function() {
$(menu + 'ul').hide();
console.log('no pokes given');
});
poked = true;
}
}
var poked = false;
$('.usa').click(function(e) {
e.preventDefault();
poked = false;
$('.usaMenu').slideToggle(500);
menuSwitch('.usaMenu');
console.log(poked);
$('.usaMenu li').on('mouseenter', function() {
if ($(this).children() != false) {
$(this).children().fadeTo(200,1);
}
else {
$('.usaMenu li>ul').fadeTo(200,0).hide();
}
});
noPoke('.usaMenu');
});
So, after spending another 6 hours researching and trying different things, I ended up with the following, which solved the problems I was having.
Hopefully this is useful to people trying to do this in the future.
var menuSwitch = function(menu) {
if ($(menu).is(':hover') === false) {
var hideMe = setTimeout(function() {
$(menu).slideToggle(500);
},4000);
}
$(menu).on('mouseenter mouseleave', function(e) {
switch(e.type) {
case 'mouseenter':
console.log('probed');
clearTimeout(hideMe);
$(this).stop();
$(this).slideDown(200);
break;
case 'mouseleave':
$(this).delay(2000).slideUp(500,function() {
$('li>ul',menu).hide();
console.log('switched');
});
break;
}
});
}
var babies = function(menu) {
$('li',menu).unbind('mouseenter mouseleave click');
$('li',menu).each(function() {
if ($('li',menu).children() != false) {
$(this).on('click',function(e) {
e.preventDefault();
$(this).children('ul').slideToggle(300);
});
}
});
}
var menuCtrl = function(menu) {
$(menu).slideToggle(500);
$(menu).unbind('mouseenter mouseleave');
menuSwitch(menu);
babies(menu);
}
$('.usa').click(function(e) {
e.preventDefault();
menuCtrl('.usaMenu');
});
Ultimately it turned out that because the initial click handler was running the functions every time it fired, it was creating duplicates of the mouseenter/leave event handlers, and therefore causing all sorts of problems. I was also trying to make the menu close if the mouse never entered, in the wrong way.
To solve the most obnoxious issue (duplicate event handlers), I simply used the unbind() api, passing it the events to unbind at the start of the function, so that when they were re-bound, there was only one instance. This may not be the most efficient way, but it works.
To solve the timing/hiding if no mouseenter issue, I used a setTimeout function, which was then cleared if mouseenter-ed.

How to open a new tab trigger by the scroll button

I'm making a php/html app which show some data in a table, when the user clicks in the row (<tr>) jquery open that record.
This is the code:
$.fn.linkRow = function(element) {
thisRow = this.find('tbody tr');
thisRow.on('click', function() {
hrefLocation = $(this).find('td.link:first a').attr('href');
if (hrefLocation) {
window.location.href = hrefLocation;
};
}).addClass((thisRow.has('td.link')) ? 'pointer' : '');
return this;
};
The fact is: The user can't open a record in a new tab. The only way is copy&paste the href... And my users won't do that.
If make some research about the event fired by the scroll button and how to open a new tab, the later is almost impossible, so... Does anyone can figure a way?
EDIT: I mean the mouse-wheel... Normally this open a link in a new tab.
PS: I have to use tables, In some point I will make a css-based table layout for that (no javascript needed), but I can't do it in this version of the software.
Thanks!
This is the final code:
$.fn.linkRow = function(element) {
thisRow = this.find('tbody tr');
thisRow.not('a').on('mouseup', function(e) {
hrefLocation = $(this).find('td.link:first a:first').attr('href');
if ( hrefLocation ) {
if (e.which == 2) {
window.open(hrefLocation);
}
else{
window.location.href = hrefLocation;
}
};
}).addClass( ( thisRow.has('td.link') ) ? 'pointer' : '' );
return this;
};
BUT... The mouse-wheel click does not work for what I intend:
If you click a link (a tag) > open a new tab
If you click a no link (any other tag) > it will scroll based on your mouse position. if you move your mouse up, it scrolls up and so
So... I works but I definitively need to make a no-javascript solution.
If you want to have the links open in a new tab and not in the same page, you need to replace
window.location.href = hrefLocation;
with
window.open(hrefLocation);
Change click with mouseup and catch e.with with value 2 (middle button):
$.fn.linkRow = function(element) {
thisRow = this.find('tbody tr');
thisRow.on('mouseup', function(e) {
hrefLocation = $(this).find('td.link:first a').attr('href');
if ( hrefLocation ) {
if (e.which == 2) {
window.open(hrefLocation);
}
else{
window.location.href = hrefLocation;
}
};
}).addClass( ( thisRow.has('td.link') ) ? 'pointer' : '' );
return this;
};
Try with the following method
$(document).scroll(function(){
if(!tabOpen){
window.open('url', 'window name', 'window settings');
tabOpen = true;
}
});
I faced a similar problem a few months ago.
Either you wrap every td-content into a normal a-Tag (and use _target="blank"), no javascript required in this case!
...or you use js:
thisRow.click(function(){
window.open('url', 'window name', 'window settings');
return false;
});
window.open() will do the trick but it also depends on the browser configuration
Not sure what you mean with the scroll button, but if it's the mouse-wheel then you can use this script to fire events on wheel-up/-down.
http://brandonaaron.net/code/mousewheel/demos
I'm unsure if you want to know how to make an middle click event with jquery or if you want to know how to open a new tab but here goes:
Middle click event:
$("tr").live('mousedown', function(e) {
if( (e.which == 2) ) {
alert("middle button");
}
e.preventDefault();
});
New tab:
As all the others are saying, use the following:
window.open(href);
With both middle click and open link:
$("tr").live('mousedown', function(e) {
if( (e.which == 2) ) {
window.open(href);
}
e.preventDefault();
});
EDIT:
Some sources:
Jquery: detect if middle or right mouse button is clicked, if so, do this:
The answer to Detect middle button click (scroll button) with jQuery can also help solve some compatibility issues with IE
To open in a new tab use:
window.open(hrefLocation);
window.open(hrefLocation,'_blank'); //Or this
window.open(hrefLocation,'_newtab'); //Or this
One of these should work.

how to detect if a link was clicked when window.onbeforeunload is triggered?

I have window.onbeforeunload triggering properly. It's displaying a confirmation box to ensure the user knows they are navigating (closing) the window and that any unsaved work will be erased.
I have a unique situation where I don't want this to trigger if a user navigates away from the page by clicking a link, but I can't figure out how to detect if a link has been clicked inside the function to halt the function. This is what I have for code:
window.onbeforeunload = function() {
var message = 'You are leaving the page.';
/* If this is Firefox */
if(/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
if(confirm(message)) {
history.go();
}
else {
window.setTimeout(function() {
window.stop();
}, 1);
}
}
/* Everything else */
else {
return message;
}
}
You're looking for deferred event handling. I'll explain using jQuery, as it is less code:
window._link_was_clicked = false;
window.onbeforeunload = function(event) {
if (window._link_was_clicked) {
return; // abort beforeunload
}
// your event handling
};
jQuery(document).on('click', 'a', function(event) {
window._link_was_clicked = true;
});
a (very) poor man's implementation without jQuery's convenient delegation handling could look like:
document.addEventListener("click", function(event) {
if (this.nodeName.toLowerCase() === 'a') {
window._link_was_clicked = true;
}
}, true);
this allows all links on your page to leave without invoking the beforeunload handler. I'm sure you can figure out how to customize this, should you only want to allow this for a specific set of links (your question wasn't particularly clear on that).
var link_was_clicked = false;
document.addEventListener("click", function(e) {
if (e.target.nodeName.toLowerCase() === 'a') {
link_was_clicked = true;
}
}, true);
window.onbeforeunload = function() {
if(link_was_clicked) {
link_was_clicked = false;
return;
}
//other code here
}
You can differ between a link unload or a reload/user entering a different address unload s by using a timer. This way you know the beforeunload was triggered directly after the link click.
Example using jQuery:
$('a').on('click', function(){
window.last_clicked_time = new Date().getTime();
window.last_clicked = $(this);
});
$(window).bind('beforeunload', function() {
var time_now = new Date().getTime();
var link_clicked = window.last_clicked != undefined;
var within_click_offset = (time_now - window.last_clicked_time) < 100;
if (link_clicked && within_click_offset) {
return 'You clicked a link to '+window.last_clicked[0].href+'!';
} else {
return 'You are leaving or reloading the page!';
}
});
(tested in Chrome)

Categories