keydown on body? - javascript

I want to get alerted whenever I press a key.
I've tried:
$('body').live('keyup', function() {
alert('testing');
});
But it doesn't work, could it be because of the selector?
UPDATE:
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>TODO supply a title</title>
<script type="text/javascript" src="../system/media/js/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('body').live('keyup', function() {
alert('testing');
});
});
</script>
</head>
<body>
<p>
TODO write content
</p>
</body>
</html>
It doesn't alert me when I press something although it works when I replace keyup with mouseover and mouse over TODO write content
Why doesn't it work?

Try using $("html") or $("*") instead of $("body"). In order for the keyUp event on body to fire, the body node or one of its children must be focused. You can accomplish this in your example by adding a text input and focusing the mouse to that input. What you really want is to capture any key press, so $("html") should work.
Edit: I think your example might work, but in any case, to run the logic conditionally you might try this:
if ($(document.body).is(".focusOnKeypress")) {
$("html").live(...);
}
Or, I think this will also work:
$("body:not(.noFocusOnKeypress)").parent("html").live(...);

Just listen to the window!
$(window).keydown(function(event){
alert(event.keyCode);
});

I tried this code. This is working fine.
$('body').on('keyup', function() {
alert('testing');
});

It does not work because your page does not have focus.. you need to click on the page first and it will work..
alternatively you could forcibly set the focus to an input element and thus bring focus to the page..
$(function(){ $('input_selector_here').focus(); });

Hope this will help.
$(document.body).on('keyup', function (e) {
alert('In');
}):

Related

JQuery $("#content").append not working

I'm trying to learn JQuery, but not doing well. Currently, I'm trying to learn how to use .append to have Ajax functionality which allows one to view new dynamic content without reloading. When I try the following, however, nothing occurs.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>JQuery Test</title>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
</head>
<body>
<div id="content"/>
<script type="text/javascript">
function callback() {
$("#content").append($("qwerty"));
};
$(document).ready(function() {
//window.setTimeout(callback, 100);
callback();
});
</script>
</body>
</html>
To the best of my knowledge, this should make "qwerty" appear as if I has simply done <div id="content">qwerty</div>, but instead I get a blank page. If I replace the .append call with alert("qwerty"), it is properly displayed. What am I doing wrong?
You are trying to find an element with tagname qwerty in the dom like <qwerty>sometext</qwerty> and append it to #content.
To append the string qwerty to #content use
$("#content").append("qwerty");
Demo: Fiddle
$("#content").append("qwerty").
Just remove $ simple in your coding.. if you want to append text, you can directly pass the text in double quotation

simple way to add onchange event to ckeditor?

Is there a nice and easy quick way to add an onchange event to the CKeditor.
I would like to do something when ever the text changes? Thanks
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script src="js/ckeditor/ckeditor.js" type="text/javascript"></script>
<script src="js/ckeditor/adapters/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
$(function () {
var config = {
toolbar:
[
['Bold', 'Italic', '-', 'NumberedList', 'BulletedList']
],
width: 600,
height: 400,
resize: false
};
$('.jquery_ckeditor').ckeditor(config);
CKEDITOR.instances[0].on('change', function () {
alert("test");
});
});
//]]>
</script>
</head>
<body>
<textarea class="jquery_ckeditor" cols="80" id="editor1" name="editor1" rows="10"><p>This is some <strong>sample text</strong>. You are using <a href="http://ckeditor.com/">CKEditor</a>.</p></textarea>
</body>
</html>
Edit. Excuse me, my previous version of answer was not correct.
As I have found out it's no a standart onchange event for CKEDITOR. Instead of it you can emulate it with help of another events for textarea. For example, you can use the event 'keydown'.
Try it by changing the code for CKEDITOR to the next one:
CKEDITOR.instances[idOfTextarea].document.on('keydown', function() {alert('text')});
More info
There is an error in your code:
CKEDITOR.instances[0]
instances is an object, and you can get value (editor) by the key.
Replace it with
CKEDITOR.instances[yourInstanceName]
CKEDITOR.instances.editor1.on('change', function() {
console.log("TEST");
});
CKEditor provides various events which is mentioned in their Documentation.
Change Event: Fired when the content of the editor is changed.
Due to performance reasons, it is not verified if the content really changed. The editor instead watches several editing actions that usually result in changes. This event may thus in some cases be fired when no changes happen or may even get fired twice.
If it is important not to get the change event fired too often, you should compare the previous and the current editor content inside the event listener. It is not recommended to do that on every change event.
Please note that the change event is only fired in the wysiwyg mode. In order to implement similar functionality in the source mode, you can listen for example to the key event or the native input event (not supported by Internet Explorer 8).
CKEDITOR.instances.editor1.on('change', function () {
// operations
});
Here editor1 is the id of the textarea or the instance of the element.

how to run click function after default behaviour of a element

My code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="jquery.js"></script>
<script>
$(function(){
$("body").on("click",".mes_sel",function(){
if($(".mes_sel:checked").length==0){
alert("Checked");
}
else alert("Not Checked");
});
});
</script></head>
<body>
<input type="checkbox" class="mes_sel">
</body>
</html>
It is alerting checked when the textbox is unchecked because onclick is running before the checking of checkbox.How can i make the click event to run after checking/unchecking of the input
Use change for that:
$(function(){
$(".mes_sel").on("change", function(){
if($(this).is(':checked')){
alert("Checked");
} else {
alert("Not Checked");
}
});
});​
Demo
Try this instead:
$("body").on("click", ".mes_sel", function() {
if ($(this).is(":checked")) {
alert("Checked");
}
else alert("Not Checked");
});​
jsFiddle example.
I ran into this problem a while back - I also found that different browsers handled this differently. Chrome was the worst offender, if I remember correctly.
This isn't necessarily the best solution, but you could attach a custom attribute to each checkbox, say "isChecked", and then base your function off this attribute like so:
if ($("mes_sel").attr("isChecked") == "true") { ... }
Like I said, not the best solution as you will have to manually flip the "isChecked" attribute in order to stay consistent with the actual checked value of the checkbox, but it will work if nothing more elegant will work for you.
If you'd like an example of this , check out this jsFiddle:
http://jsfiddle.net/NathanFriend/GAP2j/
This turns regular radio buttons into "toggleable" radio buttons - I was forced to use this custom attribute method because of the different way browsers execute onclick events.

JavaScript: trouble assigning event handlers

I'm not sure what I'm doing wrong here:
index.html
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "XHTML1-s.dtd" >
<html xmlns="http://www.w3.org/TR/1999/REC-html-in-xml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="scripts/eventInit.js"></script>
</head>
<body>
<p id="javascriptWarning">This page will not work with JavaScript disabled.</p>
</body>
</html>
eventInit.js
window.onload = function () {
alert("check"); // works
var jsWarning = document.getElementById("javascriptWarning");
jsWarning.onclick = function () {
alert("hi"); // works
};
jsWarning.onload = function () {
alert("loaded"); // fails
};
}
And yet, nothing happens. What am I doing wrong? I've tried other events, like onmouseover and onload.
I'm doing this in Visual Studio, and intellisense isn't giving me options for setting any event handlers. Is that because I'm doing this wrong?
I have confirmed that JS is working on my setup; just putting alert("hi") in a script and including it does work.
It might be important to note that I'm doing this in JScript, since I'm using Visual Studio 2010, so perhaps event handling is different?
Updated to remove '-' from the ID name, but it still doesn't work.
Updated added the window.onload block. Now onclick works, but onload doesn't.
You are trying to set a load event on a paragraph. Only objects which load external data (window, frame, iframe, img, script, etc) have a load event.
Some JS libraries implement an available event (such as YUI) — but you know the paragraph is available, since you're setting an event on it, and you couldn't do that if it was unavailable.
maybe you forgot to have the code block inside a
window.onload = function() {
// btn click code here
}
You have to wait for the document to be parsed before you can go looking for elements by "id" value. Put your event handling setup into an "onload" function on the window object.
The browser won't fire an "onload" event on your <p> tag. You won't need that anyway if you do your work in the "onload" handler for the window as a whole.
[soapbox] Use a framework.
The script is executed before the desired element exists. Additionally, I don't think, p has an onload-Event. Windows, frames and images, yes, but paragraphs?
You should use <body onload="init();"> or window.onload=function(){ … } or a library function, if you use a library. Example:
index.html
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "XHTML1-s.dtd" >
<html xmlns="http://www.w3.org/TR/1999/REC-html-in-xml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="scripts/eventInit.js"></script>
</head>
<body>
<p id="javascriptWarning">This page will not work with JavaScript disabled.</p>
</body>
</html>
scripts/eventInit.js
window.onload=function(){
alert('JS is working!');}
Edit: Okay, I am very sure, p makes no use of an onload event handler. And it's no wonder, you don't need it. If you want to execute JS code just after the paragraph is finished, do this:
<p>
<!-- stuff -->
</p>
<script type="text/javascript">
/* stuff */
</script>
Instead of this:
jsWarning.onload = function () {
alert("loaded"); // fails
};
try this
if(jsWarning) alert("loaded");
I think someone above mentioned checking for the existence of the element. At this stage the element should be present but it does no harms to check for it.
I think you have to make sure your JavaScript is binding.
Is your javascript before or after your paragraph element, for some reason my brain is aiming towards that.
I would look into using something like jQuery, it will help.
using jQuery your code would be (with the relevant jQuery files included of course):
$(document).ready(function()
{
$("#javascript-warning").click(function(){
alert("HELLO");
});
});
I don't think hyphens are valid in class names when used in conjunction with JavaScript. Try an underscore instead.
onload is a window event.

Make a link activate on doubleclick only

I'm building a very simple web-based file browser for my website.
I've styled my links to look like files and I want to be able to single-click to select them so I can do things like rename etc, and I want to be able to double-click to actually activate the link and download the file.
I've come up with the following, but it looks ugly. Does anyone have a more elegant solution?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function nullClick()
{
//do select stuff
return false;
}
function dolink(link)
{
window.location(link.href);
}
</script>
</head>
<body>
Clicky
</body>
</html>
I would avoid doing this since it goes against how users expected web sited to function, but if you must, the way you do it is the only way I know of.
Also, you should know that the site will fall back to single-clickable links if javascript is disabled or unavailable.
Clicky
I think it would be more elegant solution with one line of code.
If you're not using any JavaScript framework, that is probably as good as it gets. You could get rid of your functions thou;
Foobar
If you're not opposed to a little jQuery:
$("#yourLinkId").dblclick(function () {
window.location($(this).attr("href"));
});
How about using jQuery?
HTML example:
link1<br>
link2<br>
link3<br>
jQuery example:
$('a.dblclick')
.bind('click', function() { return false; })
.bind('dblclick', function() { window.location = this.href; });
SSCCE:
<!doctype html>
<html lang="en">
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(init);
function init() {
$('a.dblclick')
.bind('click', function() { return false; })
.bind('dblclick', function() { window.location = this.href; });
}
</script>
</head>
<body>
link1<br>
link2<br>
link3<br>
</body>
</html>

Categories