Pass on HTML element attribute to another element attribute - javascript

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

Related

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

How to simulate properly invoking a button via JS?

I'm using jQuery 1.10 in my project.
HTML:
<a id="btnStampa "class="btn btn-danger" href="" role="button" target="_blank" style="display:none;">
Print
</a>
JS:
function Print(e) {
var data = e.data.record;
if (data.token==null)
return;
$("#btnStampa").attr("href", "Ristampa41/" + data.token);
$('#btnStampa').trigger('click');
}
When I invoke Print method (within a table passing a token code) it doesn't open new window.
If set the button to visible, and I click after Print method invoked the working is that wanted
When I invoke Print method (within a grid passing a token code) it doesn't open new window.
If I set the Anchor tag to visible, and I click after Print method invoked the working is that wanted.
I also tried this code
$('#btnStampa').click();
but it doesn't work1
I need to have same behavoiur when I click on button but via JS.
Did you try click?
$('#btnStampa').click();
EDIT
Watchout: in your HTML, your ID has an extra space at the end and this must come from it ;)
By the way, I'm no jQuery expert, but did you consider using vanillaJS?
var link = document.querySelector('#btnStampa');
link.href= "Ristampa41/" + data.token;
link.click();
This works like a charm.

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. :)

Execute Javascript when link to anchor is used

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.

document.getElementById onclick only working once per page load

I have a link:
<a id="lnk" href="${pageContext.request.contextPath}/path/path2.pdf?var0=sometext&var1=moretext" onclick="update();"target="_blank">click to export</a>
and a JavaScript function in a separate file:
function update()
{
var link = document.getElementById("lnk");
link.href += "&var2=" + document.getElementById("textareaIdName").value;
return;
}
This is supposed to grab the text from a textarea box in a jsp form to pass into controller for output. It works the first time I click the link, but then if I change the text in the box and click link again it holds the same value from the first click on every other link click until I reload the page regardless of what I change in the text box. The link returns a file download.
How can I keep getting new text from textarea without reloading the page?
This occurs because you are using += each time the link is pressed which will keep concatinating the var2 onto the end of the hyperlink, to make this work you should use:
var linkName = "${pageContext.request.contextPath}/path/path2.pdf?var0=sometext&var1=moretext";
function update(obj) {
obj.href = linkName + "&var2=" + document.getElementById("textareaIdName").value;
return;
}
<a id="lnk" href="" onclick="update(this);" target="_blank">click to export</a>
In your html:
<a ... onclick="return update(this);">click me</a>
Passing this in the handler means that this in the function references the DOM element, so you don't have to use getElementById, so the function is:
function update(link) {
link.href = /* whatever */;
}
Now you can put the handler on multiple elements without knowing or using the id.

Categories