Fire event when html content change - javascript

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

Related

A simple Unobtrusive JavaScript example

<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/

Call onclick attribute programatically and talk to the event parameter

I have read the other post relating to this matter. Unfortunately it has not resolved my problem. I am happy to use jQuery, so I am looking for the cleanest solution.
I have radio buttons defined as follow:
a = 5;
input.value = "myButton";
input.onclick = (function (a) {
return function (e) {
changeSelectedRadio(e.srcElement, a);
};
})(a);
I need to be able to execute this when user click on the radio button (this works fine), and programatically.
I have tried:
$("input[type='radio'][value='myButton']").triggerHandler("click");
$("input[type='radio'][value='myButton']").click();
Both produce the same result: e (the event parameter) does not exist.
$("input[type='radio'][value='myButton']").onclick();
Does not work
Changing the input.onclick to input.click also did not work. When the use click, the function does not get triggered.
Thanks
If you're using jquery already, might as well build the inputs that way:
var input = $('<input value="something">').click(function(){
var elem = $(this); // the element clicked, as a jquery obj
alert(elem.attr('id');
});
$('body').append(input);
$('input').trigger('click');
Adjust the selectors as needed, and you'll need to actually append the elements to the DOM, but it'll work.
try this:
$("input[type='radio'][value='myButton']").bind( "click", function() {
alert( "clicked" );
});
What is passed to the function is a jQuery event, not a native event. You can use the target element to get at the source that was clicked on or use this to reference the properties of the object directly. See fiddle at http://jsfiddle.net/YQh3Q/
<p><input id="foo1" name="foo" type="radio" value="0" checked="checked"> Foo1</p>
<p><input id="foo2" name="foo" type="radio" value="1"> Foo2</p>
(function ($) {
var input = document.getElementById("foo2");
var a = 5;
input.value = "myButton";
input.onclick = (function (a) {
return function (e) {
alert(e.target + '|' + this.id);
};
})(a);
$("input[type='radio'][value='myButton']").each(function() {
$(this).trigger("click");
});
})(jQuery);
Alternatively (and probably better) you can use a pure jQuery solution
$(function() {
var a = 5;
$('input#foo2').on('click', function() {
changeSelectedRadio(this, a);
})
.val('myButton');
$("input[type='radio'][value='myButton']").trigger('click');
});
Its best to use addEventListener() you can add all types of events. example: "click", "mousemove", "mouseover", "mouseout", "resize" and many more. the false at the end is to stop the event from traversing up the dom. If you want parent dom objects to also receive the event just change it to true. also this example requires no javascript libraries. This is just plain old javascript and will work in every browser with nothing extra needed.
Also addEventListener() is better than onClick() as you can add an unlimited number of event listeners to a dom element. If you have an onClick() on an element and then set another onClick() on the same element you have overwritten the first onClick(). Using addEventListener() if i want multiple click events to trigger when i click on an element i can do it with no problem.
If you want data about the element that is triggering the event you can pass the event to the function. You will see in my example function(e) e is the event and you can use e or this to target the element that is being triggered. Using e or this i can also get more data about the triggered event. for example if the event was a mousemove or mouseclick i can get the x and y position of the mouse at the time of the event.
<!DOCTYPE html>
<html>
<head>
<title>exampe</title>
</head>
<body>
<a id="test" href="">test</a>
<script>
document.getElementById("test").addEventListener("click",function(e){
alert('hello world');
alert('my element '+e);
alert('my element '+this);
},false);
</script>
</body>
</html>
if you want to have addEventListener call a function just change the 2nd value to the function name like this.
document.getElementById("test").addEventListener("click",f1,false);
this will execute the function
function f1(){ ... }
When you want to remove an event listener just call target.removeEventListener(type, listener[, useCapture]). Very simple and easy to manage.

Toggle state of textbox with javascript using a button

I have a form as follows:
<form>
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock" onMouseDown="toggleInput()"></button>
</form>
And javascript code:
function toggleInput(){
if ($("#input").disabled){
$("#input").disabled = false;
}
else {
$("#input").disabled = true;
};
}
What I basically want to do is to check what state (enabled/disabled) the textbox is in, and then toggle the state accordingly. I don't know if the javascript portion even uses the correct syntax to check if the textbox is disabled, but it's what I could think of.
Thanks in advance!
EDIT: Reason as to why I've chosen to use onmousedown instead of onclick to execute the event with the button:
I have chosen to use onmousedown instead of onclick as it makes the app I'm building feel less clunky due to the presence of this feature with onclick: When you click on a button and then drag the cursor away from the button while holding the mouse button down, and subsequently lift your finger off the mouse button when the cursor is in an area away from the button on the webpage, the event will not be executed. Hence, I've chosen to use onmousedown as this is overcome.
Use .prop(), Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element
$("#input").prop('disabled',!$("#input").prop('disabled'))
DEMO
I am not sure why you are using onMouseDown. Use click instead
$("#lock").on("click", function() {
$("#input").prop('disabled',!$("#input").prop('disabled'))
});
DEMO with click
To do it with jQuery try this:
$("#input").prop("disabled", function(i, v) { return !v; });
Your existing code doesn't work because DOM elements have a .disabled property, but jQuery objects do not.
I'm not sure why you're using onmousedown instead of onclick for the button, but either way if you're going to use jQuery I'd recommend removing the inline event attribute in favour of binding the handler with jQuery:
$("#lock").on("click", function() {
$("#input").prop("disabled", function(i, v) { return !v; });
});
(You'd need to include that code either in a script block at the end of the body or in a document ready handler.)
Demo: http://jsfiddle.net/a7f8v/
You should append the event handler with jQuery instead of an onMouseDown event. The syntax could look like this:
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock"></button>
JavaScript:
$(document).ready(function() {
$("#lock").click(function() {
var input = $("#input");
input.prop('disabled',!input.is(':disabled'))
});
});
Example

Javascript change onmouseover to click

I have this working code, I need to change to a click instead of mouseover:
var l1OK_WC = false;
var l2OK_WC = false;
function share()
{
alert('yo');
}
function getIt_wc()
{
if(l1OK_WC && l2OK_WC)
window.open('http://google.ca','_self');
if(!l1OK_WC)
alert("Click button one");
else if(!l2OK_WC)
alert("Click Button two");
}
After this, I have this code:
onmouseover="javascript:l1OK_WC=true;"
onmouseover="javascript:l2OK_WC=true;"
How do I change this part into a click instead of onmouseover.
So they need to click instead of onmouseover.
I have tried changing to onclick but the script does not work anymore. It stays false and always displays the message of "click button one"
Unless I'm misunderstanding, it's just this simple...
onclick="javascript:l1OK_WC=true;"
onclick="javascript:l2OK_WC=true;"
You can change the HTML attribute to onclick, but that's not really best practice. Instead, why not attach an event handler to the elements in question?
Something along the lines of:
// Assuming you've already grabbed the elements and put them in the variable `myElements`
myElements.addEventListener('click', function() {
l10K_WC = true;
});
This lets you centralize your code (so you only need to make one change, instead of many throughout your HTML, as well as helps caching. For more information, see here: https://softwareengineering.stackexchange.com/a/86595/54164
Replace:
onmouseover="javascript:l1OK_WC=true;"
onmouseover="javascript:l2OK_WC=true;"
by
onclick="javascript:l1OK_WC=true;"
onclick="javascript:l2OK_WC=true;"
For more info see:
onClick and onMouseOver
Using an event listener:
<input type="button" value="Button 1" id="myButton1"/>
<input type="button" value="Button 2" id="myButton2"/>
<script>
myButton2.addEventListener("click", function() { alert('button 1 clicked!'; }, false);
myButton2.addEventListener("click", function() { alert('button 2 clicked!'; }, false);
</script>
You can use either the HTML this way:
your-element onclick="JavaScript code"
or use JavaScript to fire it...
object.onclick=function(){JavaScript Code};
If it's in a button you will have to wrap the button around it :-)
Hope this helps...

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