I have a simple wordpress navbar where I wanted to include a tel: link to automatically call the company's website.
Due to milions of issues with storing a <a> link inside the navbar I've opted for a <button> and added JS code to perform the redirecting.
document.querySelector('.btn--call').addEventListener('click', function () {
window.open('tel:' + this.innerText, '_self'); //same effect for using `_system`)
});
The problem is when I click the button I get redirected to the phone page but the number I'm calling is blank.
The variable retrieved is proper because console logging this.innerText prints the expected value.
The issue is also not with the website because I have a <a href="tel:...> in some other spot and it works like a charm.
I've tried to use window.location.href='tel:' + this.innerText; but the effect was the same.
Is there any way I could make the number properly parse without having to change it to <a>?
Any help would be greatly appreaciated.
Try this, it is accessing the element via target, instead of this on the event handler.
document.querySelector('.btn--call').addEventListener('click', function (e) {
location.href = 'tel:' + e.target.innerText;
});
Related
I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.
I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".
I'm not sure what's causing the whole page to reload.
Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.
I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.
It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like
<a href="#" (click)="$event.preventDefault()">
Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:
Html
<a href="#" (click)="someFunc($event)">
and in your ts:
someFunc(event) {
event.preventDefault();
// rest of your code here
}
This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.
I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.
So, my work around is:
#HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}
Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.
change your a tag code as below
A Tag
this will invoke yourClickEvent(); without page reload
check the stackblitz here stackblitz
If you don't want to reload the page use $event.preventDefault()
<a href="#" (click)="$event.preventDefault()">
Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.
You could also simply paste this into the console to trigger a break, and then click any of the offending elements:
['unload', 'beforeunload'].forEach(function (evName) {
window.addEventListener(evName, function () {
debugger; // Chance to check everything right before the redirect occurs
});
});
source: Break when window.location changes?
As you are using angular routes, try to use this notation:
<a [routerLink]="['./']" fragment="Test">
As explain by this comment: https://stackoverflow.com/a/38159597/4916355
use href="javascript:void(0);"
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.
ex:
// downloading the file based on file name
<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
Since you have mentioned the web app is asp.net webforms, can you please let us know
Whether the link is asp.net hyperlink control. If so,
AutoEventWireUp could cause the link to be automatically submitted:
Please have a look at this link
If you do have asp.net server controls on the page, then you could disable by setting
#Page AutoEventWireup="false"
For the entire project, this can be disabled by setting in web.config:
We want to have a back button in our site
but history.back in javascript does not help us.
We need this function only run on the site and if the user comes from other site, clicking the return button on the previous site should not return.
In fact, we want a return button to run on our site only.
my code is
<i class="fas fa-arrow-left"></i><span class="btn-text">Back</span>
This only works for your own made back button and won't work with the browser back button
There is two ways to achieve that: a simple but not always reliable method and a complex one but always good.
1- The simple method
You use document.referrer and ensure the domain is yours before calling history.back().
2- The complex method
You could register a JavaScript function on page load to get the first URL the internaut land which you could store using history.pushState. Before calling the back function, you could ensure this is not that page. Though, this idea is not complete as the user could probably have landed on this page twice. i.e. Home->Product->Home. I'll let you search for further code that would let you counter this problem.
This code checks the history of back button of the browser on its click event:
$('#backbtn').click(function () {
if (document.referrer.includes(window.location.hostname)) {
window.history.back();
} else {
window.location.href = "/your/path";
}
});
I'm currently using window.location.href.indexOf in my current project. I've noticed that it doesn't seem to work properly. For example this code that I made.
$(document).ready(function () {
//Show Sign Up drawer if user clicks on referral link
//It will show the Sign Up drawer once the word "referral" is found in the URL
if (window.location.href.indexOf("?referral") > -1) {
console.log('Sign Up Drawer');
$(".header-form-container.signup").addClass("show"),
}
});
This code what it does is to add a class in an element if the word referral is found in the URL. The add class being inserted will then slide a sign up drawer. Here is what happened during testing.
In my first test, I tried inserting the word referral in the url. After typing in the word and pressing the Enter key, the javascript I'm trying to run did not trigger
But after refreshing the browser or inserting the word again it now works. It currently shows the sign up section.
How can I ensure that the code window.location.href.indexOf will work in the first try or without refreshing the browser again. The website is built on a angular framework
If you only change the URL after the # sign, the page won't reload, since you're only changing the anchor part of the URL.
Your code wrapped in $(document).ready(function () { ... will only run once, when the page loads.
What you want to do is to add a listener for the route change event and run your code in that handler, something like this:
$rootScope.$on("$routeChangeSuccess", function() {
if (window.location.href.indexOf("?referral") > -1) {
console.log('Sign Up Drawer');
$(".header-form-container.signup").addClass("show"),
}
});
It does not work because your script (e.g: main.js) is executed only one time when the page load.
You might want to use window.historyto manipulate the browser history. You can update the query string with pushState()
History API
Hope it helps.
I have following scenario: User clicks on a link with parameter like this
www.abc.com/page1?xxx.
On page1 I would like to have script that detects parameter xxx and runs a link with a class asap (no need to wait for dom to finish, it can be in background)(running a link opens modal window with some text). I use jquery 1.8.
Edit: I am using following code: based on this question Conditionally open popup video based on URL query string
(function($){
Drupal.behaviors.zzz = {
attach: function (context) {
$(document).ready(function(){
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
if(getURLParameter('param')==1){
$(".colorbox-node").trigger('click');
}
});
}
};
})(jQuery);
However, there seems to be some loop jquery that prevents the page to finish loading. I suppose that is caused by colorbox plugin trying to set top value and looking at the console I can see "setting top" message constantly working until browser crashes. How to avoid this? Thank you
This might be a start to your question.
You can get the parameter from document.location.search. If you have multiple parameters, you might need to apply a regular expression to it.
var loc = document.location.search;
You can then open your new window
window.open(loc);
JQuery UI would be helpful in constructing a modal popup.
I've the following link:
I
And this use the following javascript:
function showGallery(){
if(window.location.hash) {
$('#gallery').fadeIn('fast');
var hash = window.location.hash.substring(1);
alert(hash);
} else {
}
}
So it only show the gallery when in the URL is a hashtag. But when i click on the link, nothing happens. When i click it twice, the gallery fade in.
So the link first make the javascript, and i doesn't work 'cause there is no hashtag in the URL and after that, it perform the href and insert the Hashtag in the URL.
How can i do that?
My Target:
When i click on a link, it open a gallery. To know which gallery i must open, i insert in the URL a Hashtag. Here i want to display the HDR album. And i also want, if my site get opend with a hashtag, it should display the gallery.!
Is there also a another, easier or cleaner way to make it?
Hope you understand what i want.
For modern browsers, you can bind your Javascript code to the onhashchange event. Links will be without Javascript:
I
And the Javascript is run whenever the hash has changed:
function locationHashChanged() {
if (location.hash === "#HDR") {
$('#gallery').fadeIn('fast');
}
}
window.onhashchange = locationHashChanged;
Have you tried a setTimeout call to delay the onclick event?
Like this:
I
You can simplify this quite considerably, it is not good practice to use the href for other things than pure navigation.
<a onClick="showGallery('HDR')">I</a>
And then:
function showGallery(name){
if(name) {
$('#gallery').fadeIn('fast');
alert(name);
} else {
}
}
If you want to run showGallery() without following the link, the correct code is this:
I
By keeping the href the user still sees the destination in the status bar and navigation still works for clients without Javascript (i.e. Google). By returning false in the event handler, you prevent the browser from following the link.
In showGallery(), you can then show the gallery and add '#HDR' to the location.hash.
You don't need to verify the window's hash, because on first click you don't have any hash in the address bar. The functionality will only apply on the second click.
What you can do is this:
gallery 1
function showGallery(galid){
var linkhash = $('#' + galid).attr('href').substring(1);
alert(linkhash);
$('#gallery' + linkhash).fadeIn('fast');
}