A simple Unobtrusive JavaScript example - javascript

<script>
var el = document.getElementById('btn');
e1.onclick=function()
{
//
alert('hello');
};
</script>
<button type="button" id="btn" >Log-in</button>
I am simply testing how unobstrusive javaScript works with a simple button onclick() event but when i click on the Log-in button nothing happens alert box doesn appears

Your script appears before the button.
It runs before the button is added to the DOM.
document.getElementById('btn') doesn't find the button because the button doesn't exist then.
Move the script after the button or put it in a function and call that function after the button exists (e.g. from the window's load event).
Also, don't rename your variables in the middle of your code. A lower case L and the numeral 1 aren't interchangeable.

The issue is you try to attach the handler before the element exists. <script> tags are executed immediately and so the browser hasn't created the button element at that time.
A solution would be to wrap it in window.onload:
window.onload = function(){
var el = document.getElementById('btn');
e1.onclick=function()
{
//
alert('hello');
};
};
Alternatively you can use the DOMContentLoaded event. This differs from onload because it doesn't wait for images and CSS to be loaded. It isn't supported by IE8 or lower though:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("ready to attach events");
});

yes as said by above 2 answers you can wrap your code in window.onload else you can write a function and call it onclick event of button as shown below
function myfunction() {
alert('Hello');
};
<input type="button" onclick="myfunction()" value="Click Me!" />
http://jsfiddle.net/wf8yJ/13/

Related

How to force click button in html5?

Something like this but instead for clicking the button have it done by calling it programmatically.
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
button onclick="myFunction()">Click me
id="demo"
I don't think "click for itself" is the right way to think about this problem. A better way would be to modularize the functionality of the button click as such:
doOnClickButton()
Then, when the page loads, simply execute this function.
Example with jQuery:
$(document).ready(function() {
doOnClickButton();
})
Following the nmg49 answer, you can do it without jQuery using the DOMContentLoaded event:
document.addEventListener('DOMContentLoaded', function() {
doOnClickButton();
});
Simply put, just skip the button part and call the function on page load. If you were doing this, use a JavaScript such as the one shown.
setTimeout(function () {
alert("Hello world!");
}, 1);

Window.onload and ordering

In the code below, I can't seem to understand the ordering of events. When I load this in the browser, I get the alert before the first div renders and the .onclick event listener cannot find the translate_button element to attach to. I thought because of the use of window.onload, my script would execute after the above html loaded. Does this have to do with the inline javascript within the html?
<div id='MicrosoftTranslatorWidget' class='Dark' id='translate_button'></div><script type='text/javascript'>setTimeout(function(){{var s=document.createElement('script');s.type='text/javascript';s.charset='UTF-8';s.src=((location && location.href && location.href.indexOf('https') == 0)?'https://ssl.microsofttranslator.com':'http://www.microsofttranslator.com')+'/ajax/v3/WidgetV3.ashx?siteData=ueOIGRSKkd965FeEGM5JtQ**&ctf=True&ui=true&settings=Manual&languages=es,pt,fr,it,tr,zh-CHS,zh-CHT,ru,de,en';var p=document.getElementsByTagName('head')[0]||document.documentElement;p.insertBefore(s,p.firstChild); }},0);</script>
<div class='disclaimer-link' id='disclaimer-link' style='display:none'>Disclaimer</div>
<script type="text/javascript">
window.onload = function () {
var button = document.getElementById("translate_button");
button.onclick = alert("lol");
};
</script>
You're assigning function execution. If you want to assign actual function you need something like
button.onclick = function() { alert("lol"); }
Another thing - you have ID defined twice for the DIV. Remove one and use the one that remains.

Fire event when html content change

I want to fire an action when there is change in html content. Below code changes html content of myId element, when click on button, so there is change in html content of myId now I want to fire another action say console.log("myalert").
<html>
<body>
<input type="button" id="buttonid" value="click">
<div id = "myId">
</div>
</body>
<script>
var button = document.getElementById("buttonid");
button.addEventListener("click", function () {
console.log("alert");
document.getElementById('myId').innerHTML = '<input type="button" id="button3" value="click2">'
});
var button2 = document.getElementById("myId");
button2.addEventListener("change", function () {
console.log("myalert");
});
</script>
</html>
How can I achieve my requirement?
Note: I don't want to use jQuery.
There is no real event for that. You could however resolve this by listening for changes in an interval loop. I wouldn't really recommend it, but it's not up to me to decide what you use in the end. It would be something in the lines of:
var myIdContent = document.getElementById('myId').innerHTML;
setInterval(function(){
if(myIdContent !== document.getElementById('myId').innerHTML){
myIdContent = document.getElementById('myId').innerHTML;
// Element has changed, do some modifications here
}
}, 1000); // Lower number for shorter intervals
However this could become terribly slow when the contents of the div grows. A better way would be to invoke an event or 'change' function whenever you change html from javascript. You have more stuff to write, but also more control over when change events occur.
Question with answers that don't involve comparing contents:
Detect changes in the DOM

javascript function execute more times when i click with jquery button

I try make button with jQuery I call the JavaScript function, but I got problem :
after page loaded, first time click on mybutton there is no reaction
second click will execute function twice
third click will execute function three
and more
Why my code execute many more ? I just want " 1 click 1 execution JavaScript function"
my code like this
<script type="text/javascript" language="javascript">
function showcase(){
var foo = function () {
alert('tutup');
};
$('#create-new').on('click',foo);
return false;
}</script> <button class="button" id="create-new"onclick="return showcase();">show text</button>
please help me out this problem
for try my full error code at here http://jsbin.com/ovucer/1/edit
You are registering multiple click event listeners to the element
Every time you click on the button you are adding a new click handler to the button using showcase method, it is not needed
<button class="button" id="create-new">show text</button>
<script type="text/javascript" language="javascript">
var foo = function () {
alert('tutup');
};
$('#create-new').on('click',foo);
</script>
This happens because you bind a click event, which calls showcase() function, which as well binds a new click event, that calls foo() method. And the last iteration is repeated every time you click the button. This is sort of recursion working here.
The right way will be to bind a click event a single time, after the element is loaded:
<button class="button" id="create-new">show text</button>
<script type="text/javascript">
$("#create-new").on("click", function() {
alert("tutup");
});
</script>
You are registering an onclick function in onclick,
use this:
$('#create-new').on('click', function(){ alert('text button'); return false; });
You're binding the click event twice. Using onclick on the HTML and over again, using jQuery .on().
To make your life easier, and as you're using jQuery already, do it just at the document ready event:
var foo = function () {
alert('text button');
return false;
};
$(function () {
$('#create-new').on('click',foo);
});
And fix your HTML bit, by removing the onclick:
<button class="button" id="create-new">show text</button>
try this in your script tag and delete the onclick event in the button:
var foo = function () {
alert('tutup');
};
$('#create-new').on('click',foo);
return false;

Can't detect changed id

When I change the id of a button I cannot find the new id with on.("click"). The function console.log() does detect that it's changed but I cannot detect it with the on() function.
HTML:
<form id="formName" action="" method="post">
<input type="submit" id="submitBtn" value="Submit" />
</form>
<button id="change">Change</button>
JS:
$("#change").on("click", function(){
$("#submitBtn").attr("id", "NewBtn");
});
$("#formName").submit(function(e){
e.preventDefault();
});
$("#NewBtn").on("click", function(){
alert("Hello");
});
So I need it to alert "Hello" after I have clicked on change. It does change the id I checked that with inspect element.
Fiddle: http://jsfiddle.net/WvbXX/
Change
$("#NewBtn").on("click", function(){
to
$(document).on("click", "#NewBtn", function(){
The reason for this is that you're wanting to use the delegate form of .on(). This call is a little different in that it takes a "string" as the second parameter. That string is the selector for your "dynamic" element while the main selector need either be a parent container (not created dynamically) or the document itself.
jsFiddle
you are setting onclick event for newBtn on load of page for the first time but unfortunately newBtn not available that time. hence after changing the id it will not trigger onclick function for newBtn.
you can do one thing to make it work, set onclick event for newBtn inside the same function where you are changing the id like below.
$("#change").on("click", function(){
$("#submitBtn").attr("id", "NewBtn");
// set on click event for new button
$("#NewBtn").on("click", function(){
alert("Hello");
});
});
.attr() function does not have a callback and thus it cannot be checked unless you setup an interval using setInterval but the function itself executes pretty soon so you are not going to need it.
For solving the problem in hand event delegation proposed by tymeJV is the right way to do it.

Categories

Resources