How to simulate properly invoking a button via JS? - javascript

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.

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

Page reloads when clicking anchor element

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:

Javascript & CGI How to open div and pass arguments in same time

I have to change my code a little bit to add jquery popup window.
So far I just open new window using:
<a href="?action=_edit&_code=code"><img src...
In new version I simply open popup window using:
<a href="#myDialog" data-toggle="modal" onclick="">...
It works in terms of open dialog box, the only problem remains is how to pass arguments from ?action=_edit&_code=code in this case ?
Thanks for help ;)
You can use more data tags, for example, data-action, and data-code. These can then be obtained in your on click handler.
This link here might give you a better idea: http://www.slideshare.net/lensco/html5-data-attributes

Span tag onclick loads blank page?

I've got a span tag:
<span id="myBtnfb"
class="demo" onclick="open()">
<span class="icon"> </span>
<span class="">Testing</span>
</span>
and some javascript
function open() {
alert('Hello');
}
Now, what I want to happen is when the span is clicked, it fires the function "open". What seems to happen though is it just reloads the page but brings back a blank page. Any ideas?
http://jsfiddle.net/qtf5s/
open() is a native JavaScript function, which opens a new page (in this case blank since there's no params specified): https://developer.mozilla.org/en-US/docs/Web/API/Window/open
Just rename your function to something like openAlert(): http://jsfiddle.net/qtf5s/2/.
Also, #Ian mentioned in the comments that in JSFiddle, it's best to change the JavaScript wrap to "No wrap - in " so that the code works.

how not to open new window on clicks after first click on link <a href="abc.jsp" target="_blank">,

I need to open a new window on first click on link .
But not to open a new windows on clicks on same link after first click.
Is there any way to solve this problem through html or javascript.
Thanks
Jyoti
Replace '_blank' with another string, e.g. 'new_window' (don't use spaces)
On further clicks the link will be opened inside the window opened onto the first click.
See (4.) inside the specification: http://www.w3.org/TR/html4/present/frames.html#h-16.3.2
<script>
var check=0;
function lanuchWindow(page){
if(check==0){
OpenWin = this.open(page);
check=1;
}
}
</script>
html code to call script:
<a href="#" onclick='lanuchWindow('pageURL.htm')'>;Launch Window</a>
This might probably help you... It will launch window for 1st time and set it's variable check to 1 and when again the link is clicked condition turns false and hence no window is launched.
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function Launch(page) {
OpenWin = this.open(page, "mywin", "toolbar=no,menubar=no,location=no,scrollbars=no,resizable=yes,width=550,height=250");
}
// End -->
</SCRIPT>
click
NOTICE: it won't work if the JS is disabled on Browser. thanks four ur reply, Andy E
<a id="foo" href="url" target="_blank">hello</a>
<script>
// add an onclick handler:
$("#foo").click(function(){
// Now remove the onclick handler so subsequent clicks don't fire it.
$(this).click(function(){});
// And set the target attribute so it opens in current window...
$(this).attr("target", "");
return true;
});
</script>
This is a better option than the ones listed above because it degrades nicely for people who don't have javascript, or want to use their middle mouse button to force opening in a new tab.

Categories