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.
Related
I've been trying to understand jQuery delegation by writing a short script, but I encountered 2 problems.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<input type="text" id="text" />
<div id="msg"></div>
<script>
function showMsg() {
if ($("#text").val() === "") {
$("#msg").html("Your input is empty");
} else {
$("#msg").html("You have entered something")
}
}
$("#text").on("blur", showMsg());
</script>
</body>
1). This event delegation doesn't work as expected, the message "Your input is empty" always shows itself indefinitely. How to fix this?
2). In the showMsg() function I have to explicitly use $("#text") for the script to work, if I use $(this) it won't work. What if I have a lot of input fields that need to use this function, is it possible to uniformly define the function so that those input fields can use it without having to change anything in the function?
All you need to do is change
$("#text").on("blur", showMsg());
to
$("#text").on("blur", showMsg);
This will also fix your $(this) problem. You can set that back now.
I'm creating a Safari extension that will stay in Safari's menubar, and upon being clicked, it will open all links containing a certain string. However, it's not working.
This is what my extension builder screen looks like: http://i.imgur.com/xRXB1.png
I don't have any external scripts set as I have the script in my HTML file, because I only want it to run when clicked.
And I have a global.html page with the following code in it:
<!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" lang="en" xml:lang="en">
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script>
safari.application.addEventListener("comnand", performCommand, false);
Function performCommand(event) {
if (event.command == "open-designs") {
$(document).ready(function() {
$('a[href*="/Create/DesignProduct.aspx?"]').each(function() {
window.open($(this).attr('href'),'_blank');
});
});
}
}
</script>
</body>
</html>
Should this not work? I'm allowed to mix jQuery and JS write, as jQuery is JS? And isn't that how I'd target the links?
The problem is that your extensions Global page does not have direct access to the currently loaded page's DOM. To be able to achieve what you need, you'll have to use an Injected Script and use the messaging proxy to talk to the page.
For instance, your global would look like:
<!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" lang="en" xml:lang="en">
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
safari.application.addEventListener("command", performCommand, false);
});
function performCommand(event) {
if (event.command == "open-designs") {
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("open-designs", "all");
}
}
</script>
</body>
</html>
And then, in Extension Builder, you'd need to add two "Start Scripts", one is jquery, the other, a new file that gets loaded into the page and looks similar to this:
function extensionname_openAll(event)
{
if (event.name == 'open-designs')
{
$('a[href*="/Create/DesignProduct.aspx?"]').each(function(index,elem) {
window.open($(elem).attr('href'),'_blank');
});
}
}
safari.self.addEventListener("message", extensionname_openAll, true);
One clear thing I'm seeing is that your $(document).ready() function is located within another function. This essentially alleviates the need for a $(document).ready() provided you only call that function once the DOM and jQuery are fully loaded.
Rearrange your code to only add the event listener once the DOM and jQuery are loaded. That is what you use the $(document).ready() callback for.
In addition there is one more issue I see with the callback function for .each(). That function needs to handle two parameters the index and the element that it references. A call to each() iterates over a collection of elements. For each element entering the callback function, its index is passed as a parameter and also the element itself that is located at that index. Check out the documentation for more info.
$(document).ready(function() {
safari.application.addEventListener("command", performCommand, false);
console.log("Document is ready to go!");
});
function performCommand(event) {
console.log("event recieved");
if (event.command == "open-designs") {
console.log("got 'open-designs' event");
$('a[href*="/Create/DesignProduct.aspx?"]').each(function(index,elem) {
console.log("opening window", index, elem);
window.open($(elem).attr('href'),'_blank');
});
}
}
You use the $(document).ready() callback as an indication that your DOM is ready and jQuery has been initialized. Once you know everything is ready, you can setup your event listener.
The function performCommand() can not be called before the listener is added (unless there is some other reference to it).
I know that this is elementary, but I'm completely unable to pass "this" as a parameter to a JavaScript function. I'm numb from trying...
<!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=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
function ko(control.id){
alert(control);
}
</script>
<body>
<div id"lala">
<a id="la" href="javascript:ko(this)" >Votes & Concerns</a>
</div>
</body>
</html>
The alert tells me "undefined!"
<a id="la" href="#" onclick="ko(this); return false;" >Votes & Concerns</a>
Don't do it from the "href" value, do it from a real event handler attribute:
<a id='la' href='#' onclick='ko(event, this)'>
Pass in the event so that you can prevent the default interpretation of a click on an <a> from being undertaken by the browser.
function ko(event, element) {
if ('preventDefault' in event) event.preventDefault();
event.returnValue = false; // for IE
// here "element" will refer to the clicked-on element ...
}
You've got it the wrong way round:
function ko(control){
alert(control.id);
}
control is the object (the DOM element object, to be precise) that you're passing with ko(this). You then want to access its id property with control.id.
NB also that there are much better ways of doing this. The best is to assign the event handlers in Javascript blocks rather than in HTML attributes. For instance:
document.getElementById('la').onclick = function() {
alert(this.id);
};
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');
}):
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>