Execute javascript function when div value changes - javascript

I have a div <div id="Country">India</div> . I want to execute some code (say JavaScript function) whenever the div value changes. How can I listen to changes on the div value? Do i need to use Jquery for this?

an easy jquery solution is to use a custom event and trigger it yourself when you change the DOM:
$("#country").html('Germany').trigger('CountryChanged');
$('#country').on('CountryChanged', function(event, data) {
//contentchanged
});

I have prepared a small demo for you. Its a little crude but I am sure You can improve it ;).
Happy Coding :)
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
$("#ChangeText").click(function(){
var value = $("#DivText").val();
$("#Country").text(value);
});
$('#Country').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
alert('Content added! Current content:' + '\n\n' + this.innerHTML);
} else {
alert('Content removed! Current content:' + '\n\n' + this.innerHTML);
}
});
});
</script>
</head>
<body >
<input type="text" id="DivText" />
<button id="ChangeText"> Change Div Text </button> <br /> <br />
<div id="Country">India</div>
</body>
</html>

You can listen to events triggered by the MutationObserver DOM API :
https://developer.mozilla.org/en/docs/Web/API/MutationObserver

Try this Demo, It's in Cracker0dks's link http://jsbin.com/ayiku and this is the code http://jsbin.com/ayiku/1/edit

Try this within script tag:
$(document).ready(function(){
var new_country1 = "";
var new_country2 = "";
var func_flag = 0;
$('#Country').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
new_country1 = this.innerHTML;
if(new_country1 != new_country2 && func_flag == 1) {
country_changed_function();
}
} else {
new_country2 = this.innerHTML;
}
func_flag = 1;
});
});
function country_changed_function(){
alert('country changed.');
}
Here "country_changed_function" is function trigger on country div innerHTML got changed.

Related

How to autorun JS on HTML load

I have the following code which is designed to capture keyboard input after the page loads. However, I'm having a problem getting the code to autorun on my website page. I've looked through other documentation and they recommend using:
window.onload = function keyboard(e)
...this is not working for me. Any help is appreciated.
<head>
<script src="jquery-3.4.1.min.js"></script>
window.onload = keyboard;
</head>
<script>
// On enter show popup with text entered
var chr = '';
$(document).on('keyup', function keyboard(e) {
chr += String.fromCharCode(e.keyCode);
console.log(chr);
$('input:hidden').val(chr);
if (e.keyCode === 13) {
alert(chr);
}
});
</script>
There's a few tricks here. All of the JavaScript code needs to be inside a script tag, and while you could use window.onload if you are using jQuery, you might as well use their .ready() function.
<head>
<script src="jquery-3.4.1.min.js"></script>
<script>
//since you have jQuery, you can define your code to run when the page is ready
$(document).ready(function(){
// On enter show popup with text entered
var chr = '';
$(document).on('keyup', function keyboard(e) {
chr += String.fromCharCode(e.keyCode);
console.log(chr);
$('input:hidden').val(chr);
if (e.keyCode === 13) {
alert(chr);
}
});
});
</script>
</head>
What is the problem?
var chr = '';
$(document).on('keyup', function keyboard(e) {
chr += String.fromCharCode(e.keyCode);
console.log(chr);
$('input:hidden').val(chr);
if (e.keyCode === 13) {
alert(chr);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The problem was with jQuery. I must have not been using the right one. Below is the correction which works.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
// On enter show popup with text entered
var chr = '';
$(document).on('keyup', function test(e) {
chr += String.fromCharCode(e.keyCode);
if (e.keyCode === 13) {
alert(chr);
}
});
</script>

If an input contains custom word, hide the button

I have an input[type=text] area and i'll paste/type a URL in it.
If pasted/typed url contains http, i want to hide $('#button') element.
If its not, keep showing the button also.
Thanks for any help.
Here is my demo code so far:
$('#pasteUrl').on('input', function () {
var str = $('#pasteUrl').val();
if (str.indexOf("http") !== -1) {
$('#button').hide();
}
});
Edit: Added "propertychange" to events as suggested by OP in the comments.
$('#pasteUrl').on('input propertychange', function (ev) {
var str = $(ev.currentTarget).val();
if (str.indexOf("http") != -1) {
$('#button').hide();
} else {
$('#button').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="pasteUrl" />
<button id="button">Go</button>
This is likely what you want - using toggle:
$('#pasteUrl').on('input propertychange', function() {
var str = $(this).val();
$('#button').toggle(str.indexOf("http") == -1);
});

Transfer href text to textbox

This is the current code I have
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body>
Active
Inactive
Banned
<input type="text">
</body>
</html>
What I want to do is when I click on active, the textbox will have the word active and so on. Is there a way to do this?
You can do this using jquery:
$(document).ready(function() {
$('a').click(function(e) {
e.preventDefault();
var text = $(this).text();
$('input[type=text]').val(text);
});
});
In pure javascript you could do this:
html - I would suggest adding an id to the input
<body>
Active
Inactive
Banned
<input id="foo" type="text">
</body>
javascript
var links = document.querySelectorAll( 'a' );
var input = document.getElementById('foo');
function setInput(event) {
event.preventDefault();
input.value = event.target.innerHTML;
};
for( var i=links.length; i--; ) {
links[i].addEventListener( 'click', setInput, false );
};
And without JQuery just in case someone wants it :
http://jsfiddle.net/s0ds5rdy/
I recommend putting "#" in the href attribute. It'll scroll to the top of the page if you don't preventDefault, while browsers might reload the page if you click on a blank link.
window.addEventListener("load", function () {
var allLinks = document.getElementsByTagName("a");
for (var i = 0; i < allLinks.length; ++i) {
allLinks[i].addEventListener("click", function (e) {
e.preventDefault();
document.querySelector('input[type=text]').value = e.target.innerHTML;
});
}
});

show/hide div when user inputs text into text area?

I am trying to toggle a div so it shows and hides when a user enters text into textarea.
i am using the below code and its not working for me, can anyone please show me why? thanks
html:
<head>
<script>
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').toggle("slow");
}
});
});
</script>
</head>
<form>
<input type="text" id="cname" name="cname" class="field">
<div id="cname2"></div>
</form>
css:
#cname2{
width:30px;
height:30px;
position:absolute;
margin-top:-13px;
margin-left:400px;
background-image: url('tick.png');
background-repeat:no-repeat;
background-position:right;
display:none;
}
so apparently my above code doesnt work in IE 9, but i should be able to achieve what i am trying to do by using this code, but can someone please show me where i place my div ID/how i adapt it to work for me?
var activeElement = null;
var activeElementValue = null;
// On focus, start watching the element
document.addEventListener("focusin", function(e) {
var target = e.srcElement;
if (target.nodeName !== "INPUT") return;
// Store a reference to the focused element and its current value
activeElement = target;
activeElementValue = target.value;
// Listen to the propertychange event
activeElement.attachEvent("onpropertychange", handlePropertyChange);
// Override .value to track changes from JavaScript
var valueProp = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype, 'value');
Object.defineProperty(activeElement, {
get: function() { return valueProp.get.call(this); },
set: function(val) {
activeElementValue = val;
valueProp.set.call(this, val);
}
});
});
// And on blur, stop watching
document.addEventListener("focusout", function(e) {
if (!activeElement) return;
// Stop listening to propertychange and restore the original .value prop
activeElement.detachEvent("onpropertychange", handlePropertyChange);
delete activeElement.value;
activeElement = null;
activeElementValue = null;
});
function handlePropertyChange(e) {
if (e.propertyName === "value" &&
activeElementValue !== activeElement.value) {
activeElementValue = activeElement.value;
// Fire textchange event on activeElement
}
};
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').show();
} else {
$('#cname2').hide();
}
});
});
One possible approach (demo):
$(document).ready(function() {
$("#cname").on('input', function() {
$('#cname2')[this.value.length > 8 ? 'hide' : 'show']('slow');
});
});
Here I assumed that in cname2 container there's some warning message, that has to be shown if length of text input is 8 or less characters. Note also that I've used oninput handler, not keyup: as it allows me to process mouse-driven cut-and-paste as well as direct input. The only drawback is that IE8 doesn't support this event (and IE9 support for it is rather buggy, as handler is not fired when character is removed from text input).
Use this Javascript function
var z = document.getElementById('cname');
z.onkeyup = function(){
document.getElementById('cname2').innerHTML = z.value;
}
Your HTML:
<input type='text' name='cname' class='field' id='cname'>
<div class='cname2' id='cname2'></div>
Checkout here: http://jsfiddle.net/iamsajeev/Q9LPv/
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').fadeIn("slow");
}
else
{
$('#cname2').fadeOut("slow");
}
});
});
http://jsfiddle.net/5EjP7/2/
I hope that helps
Try the following script:
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').toggle("slow");
}
});
});

Detecting change in hidden form field

Im writing a test code to do a counter that stores the value in a hidden form field. Whenever this counter is incremented with a button click, the counter value is stored in the hidden field. I have no problem with this portion.
However, im having problem to display an alert whenever the hidden field is being changed. Pls see my code below and tell me where i have gone wrong. Thank You.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
storage=document.getElementById('store').value;
alert(storage)
}
$(document).ready(function() {
var content = $('#store').val();
$('#store').change(function() {
if ($('#store').val() != content) {
alert('Content has been changed')
}
});
});
</script>
</head>
<body>
<input type="button" id="trigger" value="Start" onclick="startRolling()"/>
<input type="text" id="cnt" readonly="readonly"/>
<input type="hidden" id="store" value="0"/>
</body>
What if you just fire the event without trying to detect the change?
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
if(storage != tonum) {
alertChange();
}
//storage=document.getElementById('store').value;
//alert(storage)
}
function alertChange() {
alert('Content has been changed');
}
You could also look at the trigger event in jquery: http://api.jquery.com/trigger/.
Try this
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
//storage=document.getElementById('store').value;
//alert(storage)
}
$(document).ready(function() {
//var content = $('#store').val();
$('#store').change(function() {
//if ($('#store').val() != content) {
alert('Content has been changed')
}
});
Why don't you change the first function to jquery?
From the description of the change-event:
The change event occurs when a control loses the input focus and its value has been modified since gaining focus.
Hidden inputs cannot lose focus(because they never have focus), so change will not fire there anyway.
See Any even to detect when the "Class" attribute is changed for a control for a solution.
Rather than using a change event, I've used a loop event that checks every second.
var content="";
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
storage=document.getElementById('store').value;
content=storage;
alert(storage)
}
function checkifchanged(){
if ($('#store').val() != content) {
alert('Content has been changed');
}
else{
content = $('#store').val();
}
setTimeout('checkifchanged()',1000);
}
$(document).ready(function() {
content = $('#store').val();
checkifchanged();
});
var content = $('#store').val();
You are storing the changed value and comparing with the same value,
this if statement doesn't execute
if ($('#store').val() != content)
don't store the value just call change event directly.
$(document).ready(function() {
$('#store').change(function() {
alert('Content has been changed')
});

Categories