Execute Javascript when link to anchor is used - javascript

How can I execute a Javascript function when a link to an anchor is used?
I have this anchor:
<a id="localizacao" onClick="toogleShow('local')">Click here to show hidden content</a>
The user can click on this anchor to show hidden content but I would like to automatically show the content when the user clicks this link that is in another page:
<img src="dcc.png" alt="Localização" title="Localização">

You can use window.onhashchangeMDN
window.onload = checkHash; // page load
window.onhashchange = checkHash; // local click
function checkHash () {
if (location.hash === '#localizacao') {
toogleShow('local'); // <-- do stuff here
}
}

if ( location.hash === "#localizacao" ) {
// Do stuff!
}

You could add a javascript URL check for that anchor to fire when the page loads.
The Browser/HTML alone will only put that anchor into view. If you want the javascript to act on it, check the URL. Nevermind, #paislee 's answer is shorter and sweeter.

Related

Pass on HTML element attribute to another element attribute

I’m using Elementor Pro for website development. I created a standard popup that is triggered if the user clicks on a link on the page like this
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink1.com”>test link</a>
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink2.com”>test link</a>
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink3.com”>test link</a>
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink4.com”>test link</a>
The popup (on the same page) has a button that will forward the user to the external link previously clicked:
Take me to the link
Elementor offers no option to dynamically set the href value of the button based on the custom attribute (in this case “ext-link”), but I found no other option to dynamically set the href attribute of this button. Is there an easy JavaScript /jQuery escape here (no plugin!) that can be used to pass on the custom attribute value to the button link attribute?
EDIT -
I did some tryouts to fund a solution for this problem and I came up with the following:
<script>
// Append an onclick event to each link
let extLinkItems = document.querySelectorAll('[data-extlinkurl]');
extLinkItems.forEach((extLinkItem) => {
extLinkItem.setAttribute("onclick", "getUrl()");
});
The onclick event is added properly to each link here.
Because the function setLink (see below) did not work, I added some checks here:
console.log("Button count=" + document.querySelectorAll('#extlinkbtn').length); // Button count=1
console.log("Button href=" + document.getElementById("extlinkbtn").href); // Button href=http://www.test.com/
console.log("Button href=" + document.getElementById("extlinkbtn").getAttribute("href")); // Button href=http://www.test.com
These provided the expected results. The button is found and the href attribute is available.
function getUrl() {
var newUrl = event.currentTarget.getAttribute('data-extlinkurl');
console.log("newUrl=" + newUrl); // newUrl=https://www.mylink1.com
setUrl(newUrl);
}
Also works properly. When the link is clicked, the data attribute of the link is available.
function setUrl(newLink) {
let linkButtons = document.querySelectorAll('#extlinkbtn');
console.log("count=" + linkButtons.length) // count=0
linkButtons.forEach((linkButton) => {
linkButton.setAttribute("href", "'" + newLinkUrl + "'");
});
}
</script>
Here it becomes problematic. Once the link is clicked, the button cannot be found. The button is there, because the popup with the button is displayed on screen and the element visible. I'm testing several days now and either solution I tried did not work. Why is the button element found if searched on a global scope, but after the link is clicked the button is not available in the function scope?
Eventually and not thanks to the Elementor second line support, I found a solution. It seems that the content of the popup was initially loaded but deleted by a function after the DOM was loaded.
The solution was here: https://developers.elementor.com/elementor-pro-2-7-popup-events/
What I did was adding a custom data attribute to the link button that is clicked in the popup screen after this is loaded which holds the target URL. After this, I added some JS/jQuery to the popup template:
<script>
let newLinkUrl = "";
let extLinkItems = document.querySelectorAll('[data-extlinkurl]');
extLinkItems.forEach((extLinkItem) => {
extLinkItem.setAttribute("onclick", "getUrl()");
});
function getUrl() {
newLinkUrl = event.currentTarget.getAttribute('data-extlinkurl');
jQuery( document ).on( 'elementor/popup/show', () => {
document.getElementById('extlinkbtn').href=newLinkUrl;
});
}
</script>
This works perfectly

How do I add an anchor-tag to window.location?

I want to use that code here to reload the current page a user is on
<a href="javascript:window.location.href=window.location.href">...
And additionally I want the user to jump to a given anchor-tag #berechnen - how would I do that in that case?
I tried with something like so
<a href="javascript:window.location.href=window.location.href+#berechnen">
But of course that doesn't work. Do I need to save the window-location to a variable first and then add the #berechnen -string to it and then href to that variable?
In head:
<script type="text/javascript">
function redirectToAnchor(anchor) {
// We remove previous anchors from the current URL
var redirectToURL = document.URL.replace(/#.*$/, "");
redirectToURL = redirectToURL + anchor
window.location.href = redirectToURL;
window.location.reload(true)
}
</script>
Then:
<a href="javascript:redirectToAnchor('#ANCHOR')">
Personally I really dislike abusing the anchor tag by replacing its default behavior with JavaScript. By doing this, you break things like being able to open the link in a new tab, copying the link or bookmarking it.
One way you can keep this behavior and still reload the page after a click, is by adding the fragment to the href as you would do normally and in addition, you bind a JavaScript event that reloads the page when it is clicked. In that case you can simply use the href attribute to get the URL, and after you set the url, you reload the page. In the example below if the anchor has a force-reload class, it will also reload the page if you click on the anchor.
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('force-reload') && e.target.nodeName === "A") {
e.preventDefault();
window.location = e.target.href;
window.location.reload();
}
});
Click here

Is it possible to make a link to a one page webpage to open and position itself at a specific article?

Is there a way to open a specific artical via an external link and focus on it when the links open on a one page wepage?
I have a webpage that shows content as you click on links by hiding and showing the divs. What i want is to make an external link to my webpage in the form of mywebpage/(div's name) and have the link open my page but showing the content of that div right away, instead of its usual opening content you would get when clicking on just the ordinary mywebpage link.
Is it possible? And how?
Short answer: yes.
Long answer: You will have to examine the URL's hash on page load and manually translate that into hidden or shown divs (or other positioning).
While you're at it, you could include browser history support when your divs are opened and closed.
Pulling apart what I did for http://www.tipmedia.com (Segment starts on line 322 of the page source)
//on page ready
$(document).ready(function() {
//examine hash
if(window.location.hash == "#thanks") {
//scroll to an anchor tag, slight delay to insure correct page height
setTimeout(function() {
$('html,body').animate({scrollTop:$("#contact").offset().top}, 0);
},500);
//hide and show necessary divs
$("#contactThanks").css({"display":"block"});
$("#contactIndex").css({"display":"none"});
$("#contactGeneral").css({"display":"none"});
$("#contactMeeting").css({"display":"none"});
$("#contactCareers").css({"display":"none"});
//clear the hash (not necessary for your use)
window.location.hash = "";
}
}
The history stuff is easy too, I used Modernizer.js for the best cross browser support, but it looks like this (non-Modernizer use is very similar)
//during the hide/show of new content...
//if history is available
if(Modernizr.history) {
//this data is whatever it is you wish to save
lastPageState = { div:divName, pos:amount, page:lastLoadedPage };
history.pushState(lastPageState, divName.substring(1,divName.length-6), "index.html");
}
//...
//then later, the popsate event handler
window.onpopstate = function(event) {
//examine event.state and do whatever you need to
//example segment starts line 989
//Whatever data you saved would be read here and you would do the appropriate action,
//hiding or showing divs, reloading AJAX content, etc.
}
Yes, you can use an anchor link.
So in your target page name the div with an id,say div id="target".
Then in the referring page use a link in this form
Referring Page:
GO to Target Info...
Target Page:
<div id="target">
...content...
</div>
FYI-"target" is just an example name, it could be anything...

hide actual url in status bar when a link or actionlink is mouseovered or clicked [duplicate]

How can I hide URL from displaying when mouse hovers on a hyperlink?
Hyperlink
How can I hide URL from displaying in browser's bottom status bar when mouse hovers?
Don't put the URL in the href (or keep it href="#") and attach a JavaScript function to the onclick event which puts the actual link in the a element. This way you won't see the actual URL when hovering over the link but the link will be inserted when the user actually clicks.
This way you can easily hide url when mouse hover on hyperlink.
Simply add one id on anchor link.
HTML
<a href="url" id='no-link'>Hyperlink</a>
Jquery code
$(document).ready(function () {
setTimeout(function () {
$('a[href]#no-link').each(function () {
var href = this.href;
$(this).removeAttr('href').css('cursor', 'pointer').click(function () {
if (href.toLowerCase().indexOf("#") >= 0) {
} else {
window.open(href, '_blank');
}
});
});
}, 500);
});
Here is demo link https://jsfiddle.net/vipul09so/Lcryjga5/
you technically have window.status to make custom status bar messages. you can set it during an "onmouseover" event for that element and set the window.status to a blank string.. thats how we did it a long time ago however..
browsers these days prevent the modification of the status bar by default (as far as i know, firefox prevents it). so there is no guarantees as to this approach will do anything at all.
<button class="class" onclick="window.location.href='https://stackoverflow.com'">Visit StackOverflow</button>
OR
<button class="class" onclick="window.location.replace('https://stackoverflow.com')">Visit StackOverflow</button>
Just use onclick="location.href='#'"
just remove href attribute from a element. :)

How to show confirm when browser window got closed or navigated to another website in JS

As the title says ....
Sorry that some ppl got question wrong...
I want to show confirmation on these cases only:
1.Browser window is closed.
2.There is a redirect to different domain
thanks
By using the onbeforeunload event:
window.onbeforeunload = function() {
return 'Are you sure you want to navigate away from this page' ;
};
The first question has already been very well covered.
Alerts when navigating away from a web page
The second part is more troublesome. You won't get anything in the onbeforeunload event that tells you which link was clicked on to trigger it.
If you wanted to detect which link caused the close you'd have to attach some script to each link's onclick event. You'd also have to remove the href from the link and store it somewhere, you could do it like this using jQuery:
<script>
$(window).load(
function () {
$("a").each(function () {
$(this).data("url", $(this).attr("href")).attr("href", "#").click(
function () {
var destination = $(this).data("url");
// do something to check the domain, I'm just checking the whole url
if (destination == "http://norman.cx/photos/") {
alert("Not navigating to: " + destination);
} else {
alert("Navigating to: " + destination);
window.location.href = destination;
}
return false;
}
);
});
}
)
</script>
test
msft
This gets the href for each link, stores it against the link using data() and sets the link's href to "#". It then attaches a click event to each link that retrieves the url from data() and does something with it.
You could do it the other way, conditionally change the href and add the click event only on links that where on another domain.
Whether that would be a good idea or not is another question. It is at the very least an unusual thing to find yourself doing.
<body onunload="doYourThing();" >

Categories