How to detect a click as soon as possible in JavaScript? - javascript

I have the following code on my webpage:
<span id="my-id">Button</span>
<script type="text/javascript">document.getElementById("my-id").onclick = function(event) { alert("Clicked Button!"); };</script>
On my webpage, the actual code is like this:
<html>Lot of markup</html>
<button>My button</button>
<script>My one line script shown in the above snippet.</script>
<iframe>Two iframes</iframe>
<html>More HTML</html>
Since the script tag comes just after the button, it should be detecting the click but it doesn't. The click is detected only after the page has loaded. Why is that?
Is there anything that I can do to detect the click as soon as possible.

You could put the onclick event directly on the span tag. That would make it so that it works as soon as that part of the DOM has loaded, rather than waiting until the whole page has loaded to execute the script.
<span onclick="myFunction()">Button</span>
Caution:
Note that if your myFunction() is part of a script that will be loaded at the end, it still won't work. You could do something simple here, however, including the whole functionality right in the markup. For example:
<span onclick="alert('You clicked me')">Button</span>
Or something else simple.

Related

Can I use JavaScript that is called on page load to modify other elements on the page?

I work in advertising. I have a client who has a tracking tag implemented on page load on their advertiser's site. The tracking tag is just a script that calls the JavaScript contained within.
The client is running into a dilemma because they want to trigger another tag when a specific button on the page is clicked on. I don't know the reasoning, but the advertiser's web developers said that it would take them weeks to make the change and the client is aiming to get the tracking set up as soon as possible.
The client's only means of access to the advertiser's page is through the tracking tag called on page load. The client wants to call some JavaScript from the tag that fires on page load that executes a certain function with the button is clicked on. I guess this would involve writing some JavaScript to the document so that it is usable when the button is clicked on.
Questions:
1) Is this possible? In other words, can I take some JavaScript that executes on page load and use it to modify elements on the page?
2) If the button already has another onclick function attached, can we add a second one? The button has a 'class' attribute attached, so could I develop some JavaScript to search for that class attribute and append a second onclick to it? Or would that override the first one?
Note: I cannot use document.write. Would document.appendchild work? Any tips would be appreciated.
To clarify what I want to do again:
1) Trigger JavaScript file on page load.
2) From within that JavaScript file, send a function to the document/page, and attach the reference to that function to a button with a specific class attribute on the page via an onclick attribute.
3) I do not want to override any existing onclick function on the button.
Thanks,
Update:
Here's what I have so far.
<html>
<head>
<script>
function myFunction (){
//do something
}
document.getElementsByClassName('test').onclick = myFunction();
</script>
</head>
<body>
<button class="test"> Submit Request </button>
</body>
</html>
I want to make it so that when the script in the header loads, myFunction is called from the button with class "test". Am I on the right track?
Update 2: Would using setAttribute work?
<html>
<body>
<script>
function myFunction (){
//do something
}
document.getElementsByClassName('test')[0].setAttribute("onclick", "myFunction()");
</script>
<button class="test"> Submit Request </button>
</body>
</html>

javascript function reloads page upon completion

I have a simple javascript program that runs onclick of an image.
However, whenever I clicked the image, the page reloaded.
After a lot of debugging I found that the page doesn't reload until right as the script completes.
There are several setTimeouts in the code, but I noticed the page was reloading instantly. I even changed these timeouts to 15000 milliseconds, but it still reloads immediately.
I am using jquery, if it makes any difference.
I also want a different result from the program every time you click it, so that each time you click it a different script runs and a some text changes in a specific order. I did this by changing the onclick attribute of the images in each script to the name of the next script, so that script one would switch onclick to script two, and so on. I set a timeout on these switches so that one click doesn't race through every single script. script two isn't running, so that much works.
my code:
function getSounds() {
console.log("script. initiated");
$("#soundwebGetSoundDirections").html("Now, Wait until the file is done downloading and click below again.");
console.log("new message");
$("#soundwebGetSoundA").attr('href',"");
console.log("href eliminated");
setTimeout($("#soundwebGetSoundImg").attr('onclick','findFile()'),2000);
console.log("onclick to findFile()");
}
function findFile(){
console.log("FINDFILE")
$("#soundwebGetSoundDirections").html("Find the file(it's probably in your downloads), copy the path of the file (usually at the top of the file explorer) and paste in it the box below. Then, make sure there is a '/' at the end of the path and type 'Linkiness.txt' (case sensitive, without quotes) at the end. Once you have all that stuff typed, click the icon again.");
console.log("FIND IT, DARN IT!!");
$("#soundwebGetSoundPathInput").css("opacity",1);
console.log("diving into reader");
setTimeout($("#soundwebGetSoundImg").attr('onclick','readFile()'),1000);
}
function readFile(){
console.log("loading...");
$("#soundwebGetSoundDirections").html("loading...");
if(document.getElementById("soundwebGetSoundPathInput").value.length == 0){
setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);
}
}
and the HTML that's linked to,
<a id = "soundwebGetSoundA" href = "https://docs.google.com/feeds/download/documents/export/Export?id=1ynhHZihlL241FNZEar6ibzEdhHcWJ1qXKaxMUKM-DpE&exportFormat=txt">
<img onclick = "getSounds();" class = "soundwebImgResize" src = "https://cdn3.iconfinder.com/data/icons/glypho-music-and-sound/64/music-note-sound-circle-512.png" id = "soundwebGetSoundImg"/>
</a>
Thanks for any help,
Lucas N.
If you don't want clicking the image to cause the anchor tag to load the href, then move the image tag outside of the anchor tag.
You aren't using setTimeout correctly. You should be passing in a function not a statement. So, for example, instead of
setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);
you should use
setTimeout(function () { $("#soundwebGetSoundDirections").html("Please fill in Path!") },1000);
setTimeout(findFile,2000);
I think the same goes for setting the onclick attribute but I've never tried dynamically changing an onclick attribute like that.
Since you're already using jQuery you could try using .on('click'... and .off('click'... if your current setup isn't working.

javascript execute a tag on load

I have an html page with an a tag in it, and I want to know how can I make a Javascript code that executes it when the page loads (do the same action as if an user had made click on it)
Here's the code of my a tag
<div class="social-login">
<div class="btn btn-facebook">Facebook</div>
</div>
What I want is to automatically register, if possible without the user seeing the original html. (I want this because a user can get to this html from different ways, and in one of them I want to automate the registeration)
automatically register without the user seeing the original html, add code at the beginning of html
location.href="{% url socialauth_begin "facebook" %}"
Try triggering a click on the document.ready() function when using JQuery:
$(document).ready(function()
{
$(".social-login a").trigger("click");
});

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.

Loading an external .htm file into a div with javascript

So I got this code
Javascript:
<script type="text/javascript">
$(function(){
$('.ajax') .click(function(e){
e.preventDefault()
$('#content').load( 'file.htm' )
})
})
</script>
html:
Link
it works perfectly in firefox, but nothing happens when I click the link in chrome and IE simply opens a new window with the file. any advice?
I am not a coder of any sort, and I know there is more than one way to make this work.
This is what worked for me for MY situation.
I had a working site but with A LOT of code / DIV content all in one page and I wanted to clean that up.
I hope this Helps someone else!
I have been searching for this solution for quite some time and I have run across many examples of how it can work in different instances.
My scenario was as follows:
I have a photography website that uses a series of DIV tags containing the various "pages" so to speak of the site.
These were all set as:
<div id="DivId" style="display:none"></div>
The following script in the head of the page:
$(document).ready(function(){
$('a').click(function () {
var divname= this.name;
$("#"+divname).show("slow").siblings().hide("slow");
});
});
</script>
and called using the anchor links like this:
HOME
Where name was the name of the DIV to be called.
Please note the DIV will be called inside the parent container DIV.
Lastly and most importantly for this particular question and scenario, the DIV were all placed on the page as shown above.
Each div content was created just as if it were within the DIV tags but minus the opening and closing DIV tags and then saved as a separate .txt file, and called by placing this is the head of the parent page:
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js">
and
$(document).ready(function() { // this runs as soon as the page is ready (DOM is loaded)
$("#DivName") // selecting "div" (you can also select the element by its id or class like in css )
.load("PathToFile.txt");// load in the file specified
$("#AnotherDiv").load("AnotherFile.txt");// Additional DIV can be added to populate DIVs on th eparent page.
});
Change the link to href="#" or "javascript:void(0);return false;"
<a class='ajax' href='#'>...</a>
The loading logic is all in your ajax call. But, you have also a link which points to the file, too.
So, it seems that some browsers give different priorities on how the click is handled.
Anyway, links that do something other than changing page (f.ex. executing js) shouldn't have an explicit HREF attribute other than something that "does nothing" (like above)
I believe the problem is that the script loads before the document is loaded.
try this:
$(document).ready(function (){
$('.ajax').click(function(e){
e.preventDefault()
$('#content').load( 'file.htm' )
});
});
I am not sure, but i can not see any other problem.

Categories