I want to show a <div>that contains loading, using a tag-helper. I want to show the loading anywhere I have a <a> tag, except for href='#'. (I don't have any ajax call, so I will see a new rendered page after clicking the link)
$('a:Not([class="NeedsConfirmation"])').click(function () {
var currentURL = window.location.href;
var element = $(this);
if ((element.attr("href") != "#") && (element.attr("href") != currentURL))
{
showLoading(element);
}
});
Now, I want to add additional exception: currently, If user presses the ctrl and then click the link, the new page will be shown but the previews page will show loading.
How can I discard calling showLoading(element); in this case? (I have no problem with right-click and 'open in new tab' or window)
You can use the event-object passed into .click. It has a property called ctrlKey. Check it and then do the stuff you want.
$('a:not([class="NeedsConfirmation"])').click(function (e) {
e.preventDefault();
// Check if ctrl was pressed...
if(e.ctrlKey) {
// Ctrl was pressed during click
alert('ctrl click');
// Do something else.
}
else {
// Ctrl was not pressed during click
alert('not ctrl click');
var currentURL = window.location.href;
var element = $(this);
if ((element.attr("href") != "#") && (element.attr("href") != currentURL))
{
showLoading(element);
}
}
});
showLoading = function(element){
element.text('loading...');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
click me!
click me with link!
Related
I have two javascript functions. The one shows and hides div's by their ID. This has been working fine until now. I have since added some code I found online that prevents iOS from opening links in a new window (when in fullscreen mode). Since adding this new code everytime I click on a div to show/hide it, the functions fires but then the page refreshes. Any help?
I have tried to put return false in every conceivable place.
I changed my onclick to 'return function();'.
I changed it to 'function();return false'.
I placed return false inside both functions.
(function(document,navigator,standalone) {
//Code by Irae Carvalho http://about.me/irae
// prevents links from apps from oppening in mobile safari
// this javascript must be the first script in your <head>
if ((standalone in navigator) && navigator[standalone]) {
var curnode, location=document.location, stop=/^(a|html)$/i;
document.addEventListener('click', function(e) {
curnode=e.target;
while (!(stop).test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
if('href' in curnode ) {
e.preventDefault();
location.href = curnode.href;
}
return false;
},false);
}
})(document,window.navigator,'standalone');
function showHidden(id) {
var div = document.getElementById(id);
if (div.style.display == 'none') {
div.style.display = '';
}else{
div.style.display = 'none';
}
return false;
}
<!-- The code below is in my php file -->
<a onclick="showHidden('divID')">
Clicking on the link fires the showHidden function correctly but then it also refreshes the page. I need the event listener to prevent iOS from opening links in a new window when in fullscreen mode but I also don't want the click listener to fire when I use the showHidden function, or at the least not refresh the page.
The reason it is changing pages is because you are not preventing the default action of a link click, which is in this case loading a different page. You can do this by invoking e.preventDefault() when the link is clicked.
Here is an example:
(function(document,navigator,standalone) {
//Code by Irae Carvalho http://about.me/irae
// prevents links from apps from oppening in mobile safari
// this javascript must be the first script in your <head>
if ((standalone in navigator) && navigator[standalone]) {
var curnode, location=document.location, stop=/^(a|html)$/i;
document.addEventListener('click', function(e) {
curnode=e.target;
while (!(stop).test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
if('href' in curnode ) {
e.preventDefault();
location.href = curnode.href;
}
return false;
},false);
}
})(document,window.navigator,'standalone');
function showHidden(id) {
var div = document.getElementById(id);
if (div.style.display == 'none') {
div.style.display = '';
}else{
div.style.display = 'none';
}
return false;
}
var links = document.querySelectorAll('a');
links.forEach(function (el) {
el.addEventListener('click', function (e) {
e.preventDefault();
var divID = this.getAttribute('hide-id');
showHidden(divID)
})
})
<a hide-id="div1">Click here</a>
<div id="div1">
This is content
</div>
<br />
<br />
<a hide-id="div2">Click here</a>
<div id="div2">
This is content
</div>
The best solution I found to this was to add a check in the eventlistener to check if the href tag was not empty:
if(curnode.href != '' )
And only after that firing the redirect:
location.href = curnode.href;
I'm appending a string to the HREF for outgoing links on my site, it works like this. I need to append it on click because although I wrote it as a string here, it's generated at the time of click so I can't just append it to all the links before any clicking happens:
//middle-click
$(document).on("mousedown", function (e1) {
$(document).one("mouseup", function (e2) {
if (e1.which == 2 && e1.target == e2.target) {
var e3 = $.event.fix(e2);
e3.type = "middleclick";
$(e2.target).trigger(e3)
}
});
});
$('a[href*="link.php"]').on('click middleclick', function(e) {
let link = this.getAttribute('href');
e.preventDefault();
window.open(`${link}`+`&appended=1`);
});
So this works for clicks and clicks with middle mouse button BUT what about users who right-click and open in a new window/tab? How do I detect this in jquery?
I'm currently building a chrome extension and I'm trying to get it to be able to stop a like on Facebook from going through even after the like button has been clicked. In my content.js, I currently have the code:
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]').forEach(function(element) {
element.addEventListener('click', function() {
var r = confirm("You clicked like");
if (r == true) {
alert("you clicked OK");
} else {
alert("you clicked Cancel")
}
})
});
As of now, when the like button is clicked, a confirm box pops up but the like does not go through until "OK" or "Cancel" is clicked.
How do I prevent the like action from going through when the 'cancel' button is clicked? Thanks!
Try the following.
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]').forEach(function(element)
{
element.addEventListener('click', function(e) {
var r = confirm("You clicked like");
if (r == true) {
alert("you clicked OK");
} else {
alert("you clicked Cancel");
e.preventDefault();
}
});
});
For reference : https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
You could try replacing the original function with a different function of your own.
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]')[0].onclick =
e => console.log('blablabla!')
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]').forEach(function(element) {
let originalOnClick = element.onclick
element.onclick = null
element.addEventListener('click', function(e) {
console.log('look ma, no hands!')
originalOnClick(e)
})
})
Like
I tested it on Facebook and it works there too.
Obviously you have to adapt this concept to your needs.
You can use event.preventDefault()
Just add the parameter to your listener function
function(event){
...
event.preventDefault();
}
Bootstrap Warnings Image I have two different types of bootstraps alerts (warning and danger). Danger alerts are always suppose to be on the page no matter what. Warning alerts happen when user clicks on the dropdown list carriers it displays a bootstrap warning notification. User has to click on 'x' for it to close. I need it to work when user click anywhere on the page or by clicking on the 'x'.
HomeController.cs
case "Carrier":
var carrierid = (from foo in db.Carriers
where foo.ID == warningid
select foo.WarningID).Single();
if (carrierid != null)
{
warning = (from warnings in db.Warnings
where warnings.IsActive == true && warnings.Id == carrierid
select warnings.WarningBody).SingleOrDefault();
if (warning != null)
{
warning = ("<div class=\"alert alert-warning alert-dismissible\" id=\"myWarning\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button><strong>" +
warning + "</strong></div>");
}
else
{
warning = "";
}
}
else
{
warning = "";
}
return Json(warning, JsonRequestBehavior.AllowGet);
default:
break;
warningwriter.js
//// warning display script takes a value of warningid and warningcaller
$(document).ready(function () {
var warningid = 0;
var warningcaller = "Universal";
loadWarnings(warningid, warningcaller);
});
$('#Phones').change(function () {
var warningid = $(this).val();
var warningcaller = "Phone";
loadWarnings(warningid, warningcaller);})
$('#Carriers').change(function () {
var warningid = $(this).val();
var warningcaller = "Carrier";
loadWarnings(warningid, warningcaller);})
function loadWarnings(warningid, warningcaller) {
$.getJSON("../Home/LoadWarnings", { warningID: warningid, warningCaller: warningcaller },
function (warning) {
var select = $('#warnings');
select.append(warning);
});
};
As Martin suggested, it's something you need to do in javascript. I haven't tested this, but it would be something like:
$(document).click(function (event) {
$(".alert").hide();
});
This is basically, clicking anywhere on the page will hide any displayed alert.
Since you have two different types of bootstraps alerts (danger and warning). You have to use ".alert-warning" because that is the one you want to get rid of when user did a mouse click anywhere on page. ".alert" is all of the bootstraps alerts, however, if you need to get rid of a certain type you can call the contextual classes(e.g., .alert-success, .alert-info, .alert-warning, and/or .alert-danger. https://v4-alpha.getbootstrap.com/components/alerts/
$(document).click(function (event) {
$(".alert-warning").hide();
});
$(document).ready(function () {
$("#myWarning").click(function () {
$(".alert").alert("close");
});
});
By doing this, u are making two things wrong:
You are binding the click event to an element, that possibly
doesnt exist when the page is loaded.
You are binding the click
event to a restricted element. This means that the alert wont be
closed when u click anywhere on the page. In this case, only clicks on #myWarning will close the alert.
Finally, you should use what #Bryan already posted :)
Edit:
Assuming that u have a set of alerts that u always want to close on page load, add to this elements a way to identify them, for example a class "close-on-screenclick"
$(document).click(function () {
$(".close-on-screenclick.alert").alert("close");
});
.This should close those elements whenever a click is made on the screen
i have a jquery mobile app with some pages. the first page is a login page and after the user logged in i dont want the user to go back to the login page again.
after the user logged in a div called #map will be shown.
to prevent this is have the following code:
$(document).on('pagecontainerbeforechange', function (e, ui) {
var activePage = $(':mobile-pagecontainer').pagecontainer('getActivePage');
if(activePage.attr('id') === 'map') {
var test = ui.toPage;
console.log(test.attr('id');
// if(test.attr('id') === 'login' && login.status === true) {
// console.log('you are alrady logged in');
// e.preventDefault();
// e.stopPropagation();
// }
}
});
When i click previous page to go to the login page again i get this error: Uncaught TypeError: test.attr is not a function
What is wrong and how can i select the attr id of test
Sometimes the ui.toPage is a string and sometimes it is a jQuery object representing the page. Sometimes the pagecontainerbeforechange runs twice, once with the string and once with the object. So try this:
$( document ).on( "pagecontainerbeforechange", function( e, ui ) {
var from = ui.prevPage ? ui.prevPage.prop("id") : '';
var to = '';
if (typeof ui.toPage === 'string') {
var u = $.mobile.path.parseUrl(ui.toPage);
to = u.hash || '#' + u.pathname.substring(1);
} else {
to = '#' + ui.toPage.prop("id");
}
if (from === 'map' && to === '#login') {
alert('Cannot change to login from map');
e.preventDefault();
// remove active class on button
// otherwise button would remain highlighted
$.mobile.activePage
.find('.ui-btn-active')
.removeClass('ui-btn-active');
}
});
DEMO
Also, .attr("id") will work, but in newer versions of jQuery it is more correct to use .prop("id"): http://api.jquery.com/prop/