javascript onclick window.open automatically fires - javascript

The problem here is that whenever I open the page. the link is automatically opens, sometimes it opens 3 new windows without clicking the div
<div onTouchTap={window.open(a)}> TEST </div>
can you please provide your input? or suggest any other alternatives. by the way I am using ReactJS

You need to provide a function to the onTouchTap, you are actually executing window.open(a).
You could do something like:
<div onTouchTap={() => window.open(a)}> TEST </div>
I describe a similar solution and some of the caveats in another answer:
https://stackoverflow.com/a/37771414/350933

It's very common mistake. There must be a function () => {window.open(a)} or window.open.bind(null, a) as onTouchTap handler, but you are trying to put function call here, so it calls every time when your div rendering

Related

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:

Attaching an event listener for left or right click - onclick doesn't work for right click

I am currently applying for an Internship Internship Link
One of the things that I noticed right away is that you click on upload cover letter or paste cover letter, you're redirected to the home page of the job invite site Job Invite and sadly you can't upload your cover letter. On the other hand, the upload resume works perfectly fine but paste resume has the same issue.
Does anyone know how to resolve this issue and and be able to submit a cover letter?
I am not a web guru but since I am applying for an engineering position, I am trying to find a way around this. I right clicked the upload cover letter link and inspected the link with the inspect element tool. I found that this function
onclick="jvAddAttachment2('jvcoverletter', 'qLY9Vfwx')
was going to get called when the button is clicked. Now going into the JavaScript file for this html page, Inspect Element -> Sources -> *careers_8.js?v=303, I tried to do a basic alert statement, from alert dialog, to do some debugging to see what the issue is. Here's the code now
function jvAddAttachment2(id, companyId){
alert("I got here");
....
}
I then did control s and the Inspect Element console outputted "Recompilation and update succeeded." so I am assuming the JavaScript file has been updated. However when I click the link(via right click, open new window), no alert box shows up. Does anyone know how to get the alert dialog to show up? I think I've done as much as I can with my working knowledge from one web development course haha.
You're looking for the contextmenu event for right click:
element.addEventListener('contextmenu', function() {
// code here
});
Please don't use inline js, like onclick in your html. The above sample is the proper way to attach event listeners.
You should get your element reference in javascript with var myElem = document.getElementById('the-id') or some similar function like document.querySelector, etc.
Then, you can easily attach both events like this:
// left click
myElem.addEventListener('click', myFn);
// right click
myElem.addEventListener('contextmenu', myFn);
If you're adamant to do this with inline js, that would be:
<div onclick="myFn()" oncontextmenu="myFn()"></div>
Full demo of both approaches for ya:
var myElem = document.getElementById('my-element');
myElem.addEventListener('click', myClickFn);
myElem.addEventListener('contextmenu', myClickFn);
function myClickFn() {
console.log('this is myClickFn!');
}
function someFn() {
console.log('this is someFn!');
}
<div id="my-element" onclick="someFn()" oncontextmenu="someFn()">Left or Right click me!</div>
Also, since you're wanting to pass parameters to the function you'll be calling on click, it is good to use an intermediary function for the event, and have that function call the other function, passing the parameters, like this:
function myClickFn() { // this is called on click
myOtherFunction('some', 'params');
}
That prevents you having to repeat the same function call, passing those same parameters in both places.
Make sure to close your onclick string at the end with a ":
onclick="jvAddAttachment2('jvcoverletter', 'qLY9Vfwx')"
And left click instead of right clicking.
onclick="jvAddAttachment2('jvcoverletter', 'qLY9Vfwx')"
I think that double quotation was absent.
demo

Completely delete all instances of a div with a specific class using javascript/jquery?

I am using Popup.js by Toddish.
http://docs.toddish.co.uk/popup/demos/
Long story short, the popup plugin creates divs by default given the classes ".popup_back" and ".popup_cont".
I have another button I wish to press which should completely delete the added divs with those classes after they have been generated and added to the html. As if they never even existed. Surely this is possible?
I have tried running a function which simply runs:
$(".popup_back").remove();
$(".popup_cont").remove();
As shown in this example:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_dom_remove
Unfortunately despite the code running, the actual divs are never deleted as required.
Any ideas? I am new to this kind of thing and have googled around and read a lot about DOM etc but am yet to crack it.
Thanks
EDIT:
In reply to the comments:
The Javascript:
function removePopups() { // This function is called to remove the popups.
console.log("removing...");
$(".popup_back").remove();
$(".popup_cont").remove();
}
function func(url) { // url is the url of the image to be displayed within the popup.
removePopups(); // As soon as the function casillas is called, removePopups is used to remove any existing instances of the divs.
$('a.theimage').popup({ // This is where the Popup plugin is utilised.
content : $(url),
type : 'html'
});
}
The HTML:
<a class="theimage" onclick="func('image/image1.jpg')" href="#" >
Long story short, an image is displayed in the popup.
I think the issue is that the popup plugin runs due to the class but the function func is never actually run when the click occurs. However simultaneously "removing..." still prints out in the console which tells me that the function IS being executed. The problem is I want the popup plugin to run together with the javascript function. Is there a solution for this conflict?
Your implementation should really be as simple as this:
<a class="theimage" href="#" >Open</a>
Bind the popup creation to your popup link:
$('a.theimage').popup({
content : 'image/image1.jpg',
type : 'html'
});
I'm speculating here, but what might be happening is that you're invoking the popup twice by binding the popup() call to a click handler in your markup. The popup plugin already binds the popup creation to a click event.
View working demo. Note the 3 external resource: the popup CSS, the popup JS, and the jQuery JS.

Sending a form request in Python

I am trying to simulate a button click in Python on a website, when that button is clicked it adds some stuff to the end of the URL and returns false. If I add the stuff to the end of the URL it takes me to the right place but doesn't register that the button was click which is why I think I need to use the return false part.
Here is the exact code for the button and the button area. I don't know if this is actually doing anything or just setting up the button and waiting for the javascript to actually do the execution.
<div class="contractLink"><button type="button" value="upgrade to level 3"id="button533e24e4d7c79" class="green build" onclick="window.location.href = 'dorf1.php?a=16&c=fb5ad7'; return false;">
<div class="button-container addHoverClick">
<div class="button-background">
<div class="buttonStart">
<div class="buttonEnd">
<div class="buttonMiddle"></div>
</div>
</div>
</div>
<div class="button-content">upgrade to level 3</div>
</div>
</button>
This is where the script is that gets run when the button is clicked. I basically want to simulate the button being clicked through a python script which should go to a different URL and say "it's upgraded" (not literally say "it's upgraded" but make the website think it is and start the upgrading process)
<script type="text/javascript">
window.addEvent('domready', function()
{
if($('button533e24e4d7c79'))
{
$('button533e24e4d7c79').addEvent('click', function ()
{
window.fireEvent('buttonClicked', [this, {"type":"button","value":"upgrade to level 3","name":"","id":"button533e24e4d7c79","class":"green build","title":"","confirm":"","onclick":"window.location.href = \u0027dorf1.php?a=16\u0026amp;c=fb5ad7\u0027; return false;"}]);
});
}
});
</script>
Any help would be great, thanks for your time.
This is an alternative to using Python; this might be useful to those wishing to have a button click simulation without having normal subsequent action take place at the testers discretion.
Assuming that the id of the button to be simulated is "button533e24e4d7c79", the jQuery library has the trigger method to trigger the click (or any supported event for that matter) of this button:
$("#button533e24e4d7c79").trigger("click"); // This will mimic the clicking of the button (programmatically) -- requires Jquery
My understanding is that the trigger method will invoke the "click" event and stop at the event handler (i.e., won't follow links, won't continue with form submission, etc.). I haven't fully tested, but that's my understanding.
If it's desired to fully simulate the button click, jquery.simulate.js library (https://github.com/eduardolundgren/jquery-simulate/blob/master/jquery.simulate.js) provides the simulate method to allow following of links, etc.
The jQuery learning page at http://learn.jquery.com/events/triggering-event-handlers/ provides the proper explanation.

Check if the webpage has been modified

I am working on chrome extension for facebook. If you use facebook, you know that when you scroll down to the bottom of the news feed/timeline/profile it shows more posts. The extension actually adds a button beside the "like" button. So I need to check if there are more posts to add that button to.
Right now to check if the page has been modified, I use setInterval(function(){},2000).
I want to run a function when the user clicks the button. But this function doesn't work if I put it outside (or even inside) setInterval() – The Koder just now edit
How can I check if the webpage has been modified WITHOUT using a loop?
Example:
$(document).ready(function(){
window.setInterval(function(){
$(".UIActionLinks").find(".dot").css('display','none');
$(".UIActionLinks").find(".taheles_link").css('display','none');
$(".miniActionList").find(".dot").css('display','none');
$(".miniActionList").find(".taheles_link").css('display','none');
//only this function doesn't work:
$(".taheles_link").click(function(){
$(".taheles_default_message").hide();
$(".taheles_saving_message").show();
});
//end
$(".like_link").after('<span class="dot"> · </span><button class="taheles_link stat_elem as_link" title="תגיד תכל´ס" type="submit" name="taheles" onclick="apply_taheles()" data-ft="{"tn":">","type":22}"><span class="taheles_default_message">תכל´ס</span><span class="taheles_saving_message">לא תכלס</span></button>');
$(".taheles_saving_message").hide();
}, 2000);
});
In the future, this extension will use AJAX, so setInterval() can make even more problems for me.
If I understand correctly you want to get a notification when the page's DOM changes. And you want to do this without using the setInterval() function.
As your problem lies within the attaching event handlers to elements that are created after the page has loaded, you might be interested in checking out the jquery.live event attachment technique. I think it will solve your issue.
In general you want the page to throw a mutation event. There is a mutation event spec that might be what you're looking for. Here are some links that might be useful.
http://tobiasz123.wordpress.com/2009/01/19/utilizing-mutation-events-for-automatic-and-persistent-event-attaching/
Detect element content changes with jQuery
$(document).ready(function(){
setInterval('fun()',5000);
fun();
});
function fun()
{
alert(11)
}

Categories