<!DOCTYPE html>
<html>
<head>
<script>
function init() {
document.getElementById("inputname").id = 'newinputname';
document.getElementById("newinputname").onchange = function() { Test() };
}
function Test() {
alert('Test');
}
</script>
</head>
<body onload='init()'>
Enter your name: <input type="text" id="inputname">
</body>
</html>
I can't to seem to find any way of viewing the altered page. For example in the above example, which has no purpose other than to illustrate, I would like to be able to see the effect of the onchange reflected. With say IE and F12 tools I can see the name change to the input element but can't see the onchange anywhere.
I have a piece of code which alters a table significantly, changes ids and sets onclick handlers. I would like to check that the changes have gone through. As above I can see the id alterations etc have worked OK and the onclick functions seem to work OK but I can't see where the onclick="..." has been entered in the new page output.
I think I may have some basic misunderstanding. Any help gratefully received.
Rather than adding attribute onchange, assigning document.getElementById("newinputname").onchange sets new event listener.
If you want to see events connected to element, you will have to use console.log and similar tools. See this answer: How to find event listeners on a DOM node when debugging or from the JavaScript code?
Related
I want to put text into a textarea input element using key events in jquery. I know that it can be simply done with .val() or .html() functions but there's a reason that I want to put text using keyevents. The following is my code:
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p>In this example, the text field gets focus immediately after the document window has been loaded.</p>
<textarea id="myText"> </textarea>
<script>
$(function() {
document.getElementById("myText").focus();
$('#myText').focus().trigger({ type : 'keypress', which : 65 });
$('#myText').trigger(jQuery.Event('keypress', { keyCode: 65 }));
});
</script>
</body>
</html>
I have googled it and realized that there is two different ways of triggering events using jquery. I tried both but neither of which seem to be working.
It looks like your keypress event is getting fired, but since it is only an event I don't believe it is actually going to input your value into the field. If you're expecting something to happen on the keypress event from some other code you have, then there is some other issue.
If you demo with this fiddle you'll see the keypress event firing.
Try the code below to change the value of the input field with the new keypress value:
$(function() {
$('#myText').trigger(jQuery.Event('keypress', { keyCode: 65 })).val($("#myText")
.val() + String.fromCharCode(65));
});
The question is answered over there. Being short - key events won't change the actual input due to security reasons, but there is a plugin called "The $.fn.sendkeys Plugin" which can help you with a workaround.
Surely the answer to this is simple but I can't explain it so I ask it here.
https://jsbin.com/tuzifobale/edit?html,css,js,output
I'm trying to make a div have class added when you click on it and if the div has that class it then X function (in this case it's fadeout) happens, thus clicking on it makes X function happen.
How does chronology work in Javascript? Are there any links for reading I can get that can make me understand when and how things become applicable? Thanks.
welcome to StackOverflow.
You should take more precautions when writing your question, and make sure that it is written in good English, and in a way so that someone who does not priorly know what you want to achieve can understand your goal when reading the question.
I'm gonna try to answer to the parts I think I understand.
if the div has that class it then X function (in this case it's fadeout) happens
What I understand is that you would like to trigger the execution of function X when the <div> receives a class (clicked?).
Watching a DOM element's class value changes in Javascript is a problem that doesn't seem to have a reliable solution. (See related questions.)
thus clicking on it makes X function happen.
Maybe your goal is actually simpler. If you only want to trigger the execution of a function when you click on the <div>, then you'll have to look at mouse event handlers, especially .click() that allows to
Bind an event handler to the "click" JavaScript event
Few things I found in you JsBin are as below,
Always include js files in Head or before element get loaded like below
You can not find, if element is click or event is triggered in if condition like you did in for loop
What is there in else?
See below and check if it helps you
$(document).ready(function(){
$('div').animate({left:'200px'});
$('div').animate({top:'200px'});
$('div').animate({left:'px'});
$('div').animate({top:'-100px'});
$('div').animate({top:'200px'});
$('div').animate({left:'0px'});
$('div').animate({top:'0px'});
$('div').on('click', function(){
$(this).addClass('clicked');
$(this).stop(); //Stop animation
});
});
div {width:100px; height:100px; background:red; position:relative}
.clicked {
background: green;
}
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
</head>
<body>
<div></div>
</body>
</html>
I'm trying to trigger an event handler when a script modifies an input element (text field.) On Internet Explorer, I can use the onpropertychange event, but on Firefox and other browsers there is no such event. So, according to the W3C docs, it seems the DOMAttrModified event does exactly what I want. But it doesn't fire in Firefox 11.
Here's a simple code snippet which reproduces the problem. I have an input text field, and a button which adds a character to the value attribute of the input text field. Clicking on the add char button should cause the DOMAttrModified event to fire:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function addChar() {
var q = document.getElementById("query");
q.value += "X";
}
function loadevents() {
var q = document.getElementById("query");
q.addEventListener("DOMAttrModified", function() {alert("DOMAttrModified event!");
}, false);
}
</script>
</head>
<body onLoad="loadevents()">
<input type="text" id="query">
<br>
<input type="submit" value="add char" onclick="addChar()">
</body>
</html>
But it doesn't. Any idea what I'm doing wrong? (I know that DOM Level 3 deprecates this event, but there doesn't seem to be a viable alternative right now. As far as I know, Firefox 11 still supports it.)
Changing the value in an input doesn't fire the DOMAttrModified event, that's all..
You need to change the attribute of the input node, not the property of the variable.
It's like the difference between the two jQuery functions: .prop and .attr
Read:
Which HTMLElement property change generates DOMAttrModified?
this forum discussion
(repeating my answer from Which HTMLElement property change generates DOMAttrModified? here, because it's relevant to this question):
Please also note that NO DOMAttrModified events will be fired when the 'disabled' attribute is set. So if your event is not firing, that could be the reason. This also goes for the IE-only 'onPropertyChange' event.
I am currently developing Unit Tests for a Javascript method that detects the readiness of the document. This code is already at framework level, so please avoid mentions of this being already implemented in jQuery or another library.
I have successfully simulated the 'readystatechange' change event with the following code:
var event;
event = document.createEventObject();
event.type = 'readystatechange';
document.fireEvent('onreadystatechange',event);
I failed to do the same for the 'load' event. The following code results in an invalid argument error in IE7, thrown by the call to fireEvent on the last line:
event = document.createEventObject();
event.type = 'load';
document.fireEvent('onload',event);
Has anyone done this, or failed to do this before? I am also interested in any suggestion to fire the event in a different way.
Edit: following the suggestion by Crescent Fresh, I changed my code to:
event = document.createEventObject();
event.type = 'load';
document.body.fireEvent('onload',event);
There is no more error, but the listener for 'onload' does not fire. Here is how I configured it:
document.attachEvent('onload',listener);
According to this page at MSDN, there's no onload event for document.
You want either window.onload or document.body.onload. These are identical in IE: for historical reasons, <body onload="..."> actually sets window.onload, so MS decided to make document.body.onload an alias of window.onload.
The problem with this is - as Eric mentioned in the comments - that there doesn't seem to be a way to manually fire window events, which means that there might not be a solution for Eric's problem.
For some reason, it appears that IE overrides the onload property of window with an empty object after the DOM is loaded. At least that is the case when you try to access it from within any event handler of a DOM element...
<!DOCTYPE html>
<html>
<head>
<title>Test by Josh</title>
<script type="text/javascript">
window.onload = function() {
alert("Test");
}
alert(typeof window.onload);
</script>
</head>
<body>
<h1 onclick="alert(typeof window.onload);">Test</h1>
</body>
</html>
In this situation, you'll see that window.onload is recognized as a function initially, then you see the "Test" alert. When you click on the heading, you'll see that window.onload is now an object. I tried iterating through the properties of the object, but it's empty. This is not cool.
One lame workaround is to grab the function in the accessible scope and assign it to a different property that you can fire at your convenience...
<!DOCTYPE html>
<html>
<head>
<title>Test by Josh</title>
<script type="text/javascript">
window.onload = function() {
alert("Test");
}
</script>
</head>
<body>
<h1 onclick="window.onloadfix()">Test</h1>
<!-- Could potentially be injected via server-side include if needed -->
<script type="text/javascript">
window.onloadfix = function() {
window.onload();
}
</script>
</body>
</html>
I can't think of any other way to address this issue right now.
The load event will fire when the document (including external resources such as images) has fully loaded, and not before.
What results are you getting from your attempts to fire readystatechange? Does the readyState value actually change at all? Whether or not, that's not of much use either: either you fire the event with a readyState that hasn't changed, or you do so with a readyState that isn't a valid reflection of the state of the document.
I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great.
Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads.
The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?
Let me guess: the help "icon" is actually a link with a javascript: url? Change it to a real button, a real link, or at least put the functionality in an onclick event handler (that prevents the default behavior). Problem solved.
<!-- clicking this link will do nothing. No onbeforeunload handler triggered.
Nothing.
And you could put something in before the return false bit...
...and the onunload handler would still not get called... -->
blah1
<!-- this should also do nothing, but IE will trigger the onbeforeunload
handler -->
blah2
EDIT: My "workaround" below is complete overkill, based on my lack of understanding. Go with Shog9's answer above.
OK so while I was writing the question, I came up with a workaround which will work for now.
I put a global JavaScript variable in act as a boolean on whether or not the icon is being hovered over. Then, I attach events to the image's onmouseover and onmouseout events and write functions that will set this value. Finally, I just code in the function that handles onbeforeunload that will check this value before setting event.returnValue.
Probably not a flawless workaround but it will work for now.
on the internet you will find many people suggesting you use something like
window.onbeforeunload = null
but this does not work for me in IE6. reading up in the MSDN docs for the event object i found a reference to the event.cancelBubble property, which i thought was the solution. but thanks to Orso who pointed out that setting "event.cancelBubble=true" is useless, the way to get rid of the confirm prompt is to exclude the return statement altogether, i chose to use a boolean variable as a flag to decide whether to return something or not. in the example below i add the javascript code programattically in the code behind:
Page.ClientScript.RegisterStartupScript(typeof(String), "ConfirmClose", #" <script> window.onbeforeunload = confirmExit; function confirmExit() { if(postback == false) return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons.""; } </script>");
then the help button contains the following aspx markup:
OnClientClick="postback=true;return true;
this sets the 'postback' variable to true, which gets picked up in the confirmExit() function, having the effect of cancelling the event.
hope you find this useful. it is tested and works in IE6 and FF 1.5.0.2.
I have a method that is a bit clunky but it will work in most instances.
Create a "Holding" popup page containing a FRAMESET with one, 100% single FRAME and place the normal onUnload and onbeforeUnload event handlers in the HEAD.
<html>
<head>
<script language="Javascript" type="text/javascript">
window.onbeforeunload = exitCheck;
window.onunload = onCloseDoSomething;
function onCloseDoSomething()
{
alert("This is executed at unload");
}
function exitCheck(evt)
{
return "Any string here."}
</script>
</head>
<frameset rows="100%">
<FRAME name="main" src="http://www.yourDomain.com/yourActualPage.aspx">
</frameset>
<body>
</body>
</html>
Using this method you are free to use the actual page you want to see, post back and click hyperlinks without the outer frame onUnload or onbeforeUnload event being fired.
If the outer frame is refreshed or actually closed the events will fire.
Like i said, not full-proof but will get round the firing of the event on every click or postback.