on a web page how do you enable the user to light up the boxes/items on the page using a specific key on your keyboard? eg. i want M to light up my title and when i press M again it turns it off?
this is what i have so far but feel like it could be cleaned up a lot
$('#abutton').click(function() {
$('#abutton').removeClass('off').addClass('on');
$('#bbutton').removeClass('on').addClass('off');
$('#cbutton').removeClass('on').addClass('off');
$('#dbutton').removeClass('on').addClass('off');
window.scrollTo(0,0);
});
$('#bbutton').click(function() {
$('#abutton').removeClass('on').addClass('off');
$('#bbutton').removeClass('off').addClass('on');
$('#cbutton').removeClass('on').addClass('off');
$('#dbutton').removeClass('on').addClass('off');
window.scrollTo(0,0);
});
$('#cbutton').click(function() {
$('#abutton').removeClass('on').addClass('off');
$('#bbutton').removeClass('on').addClass('off');
$('#cbutton').removeClass('off').addClass('on');
$('#dbutton').removeClass('on').addClass('off');
window.scrollTo(0,0);
});
$('#dbutton').click(function() {
$('#abutton').removeClass('on').addClass('off');
$('#bbutton').removeClass('on').addClass('off');
$('#cbutton').removeClass('on').addClass('off');
$('#dbutton').removeClass('off').addClass('on');
window.scrollTo(0,0);
});
Just add the general class .button to all of them. Then remove on from all .button elements and add on class to exact clicked element.
$('.button').click(function() {
$('.button').removeClass('on').addClass('off');
$(this).removeClass('off').addClass('on');
window.scrollTo(0,0);
});
You need to add addEventListener to your code and check inside it if the pressed key has keyCode you're expecting to do some action. Look on example below:
addEventListener("keydown", (event) => {
if (event.keyCode === '13')
//light on/off
});
Please check docs for more details
EDIT: jQuery also has its keyboard events
So I have the following code:
JS
function overlay() {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
return true;
}
$("#close-link").click(function(event) {
event.preventDefault();
var targetUrl = $("#confirm").attr("href");
});
$("#confirm").click(function(event) {
event.preventDefault();
});
$("#go").click(function(event) {
event.preventDefault();
});
HTML
<div id="overlay">
<div id="dialog">
<h3 class="top-bar">Leaving so soon?</h3>
<span class="close-button-container">[X]</span><br /><br /><br />
Example text
<br />No, take me there anyway...
</div>
</div>
<!-- ... -->
Example Link
The Problem
I tried adding a link to another site. But I wanted to add a confirmation box once this link is clicked. The #close-link is used to close the dialog and the #confirm link as seen above should open it. The #go link is inside the dialog and if clicked brings the user to the location of the #confirm link. But something went wrong... Now when I click #confirm it opens the dialog for a second and directly sends me to its href. Shouldn't event.preventDefault fix this? If so, then why doesn't it?
Add an event to overlay(event). This function needs to prevent the click so it should have the e.preventDefault()
Example Link
function overlay(event) {
event.preventDefault();
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
var href = event.target.href
//If click button close
//Hidden div, no go
//If click button go
//window.location = href
}
Explanation
Your <a> has two events binded to it. One with #confirm and one with the inline onclick=. You should choose only one :)
So, a few things;
Remove all inline event handlers
When using jQuery, make the most of it and avoid writing vanilla javascript unless there is a reason to do so.
Do not use A for any other purpose than an actual link (The close button in your case). Use a button/other tags.
Take a look the below code and see if that's what you wanted.
$("#confirm, #close-link").click(overlay);
function overlay(evt) {
evt.preventDefault();
var el = $("#overlay");
el.css({"visibility": el.css("visibility") === "visible" && "hidden" || "visible"});
if ( this.tagName === 'A' ) {
el.find("a").attr("href", this.href);
}
}
#overlay {
height: 150px;
width: 200px;
background: green;
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="overlay">
<div id="dialog">
<h3 class="top-bar">Leaving so soon?</h3>
<span class="close-button-container" id="close-link">[X]</span><br /><br /><br />
Example text
<br />No, take me there anyway...
</div>
</div>
<!-- ... -->
Example Link
If your code was called as part of an event listener callback, event.preventDefault() would work. But your code is running due to onclick which simply runs the function overlay() - attaching listeners to various elements (#close-link, #go, #confirm) using jQuery. After the listeners are attached, they start listening for events, which never come since the <a href="..."> changes the page.
Solution:
It is best to stop using on* attributes for all your codes. Take it out. Then use only event listeners for all your needs.
$('#confirm').on('click', function(event) {
event.preventDefault(); // this will work
// Do your toggle visibility and whatever else you need here.
});
There are other possible solutions that continue to use onclick calling a function, but I wouldn't recommend it.
Try attaching the click event to the #confirm element inside $(document).ready:
$(document).ready(function() {
$("#confirm").on("click", function(event) {
event.preventDefault();
});
});
I want click event to be distinguished between the click on modal dialog with the click of the background of modal dialog for some purpose.
Please help !
Thanks a ton in advance.
I can't find any built in function to obtain what you want; the only "hacky" way I found is to check the click/keyup event of the document and if the modal is opened call your callback.
Code:
$(document).keyup(function (e) {
if (e.which == 27 && $('body').hasClass('modal-open')) {
console.log('esc')
}
})
$(document).click(function (e) {
if (e.target === $('.modal-scrollable')[0] && $('body').hasClass('modal-open')) {
console.log('click')
}
})
Demo: http://jsfiddle.net/4zzKz/
The alert is working, but the button just won't click...
$('#loginDialog .field input').keyup(function (e) {
if (e.keyCode == 13) {
alert('it is working!');
$('.ui-button').click();
return false;
}
});
I have tried many different things, including reinitializing the method when the dialog gets opened, but nothing seems to work...
Html:
<div id="loginDialog" title="Please Login">
<div class="label">Password:</div>
<div class="field"><input type="password" /></div>
</div>
the ui-button is generated by jquery ui
I'm assuming from your comment that the button is generated dynamically and that any click event you have bound to is will have to be bound using event delegation, similar to:
$('body').on('click', '.ui-button', function(){...)
Instead of body, using the closest static element will work as well and would be preferred.
Please, try this:
$(function() {
$('#loginDialog .field input').keyup(function (e) {
if (e.keyCode == 13) {
alert('it is working!');
$('.ui-button').trigger('click');
return false;
}
});
$('.ui-button').click(function() {
alert('hello world');
});
};
Here there is an example: http://jsfiddle.net/netme/YZH3B/
This should trigger the event ...
$('.ui-button').trigger('click');
Is there any event in Jquery that's triggered only if the user hits the enter button in a textbox? Or any plugin that can be added to include this? If not, how would I write a quick plugin that would do this?
You can wire up your own custom event
$('textarea').bind("enterKey",function(e){
//do stuff here
});
$('textarea').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
http://jsfiddle.net/x7HVQ/
$('#textbox').on('keypress', function (e) {
if(e.which === 13){
//Disable textbox to prevent multiple submit
$(this).attr("disabled", "disabled");
//Do Stuff, submit, etc..
//Enable the textbox again if needed.
$(this).removeAttr("disabled");
}
});
Here is a plugin for you: (Fiddle: http://jsfiddle.net/maniator/CjrJ7/)
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
//use it:
$('textarea').pressEnter(function(){alert('here')})
heres a jquery plugin to do that
(function($) {
$.fn.onEnter = function(func) {
this.bind('keypress', function(e) {
if (e.keyCode == 13) func.apply(this, [e]);
});
return this;
};
})(jQuery);
to use it, include the code and set it up like this:
$( function () {
console.log($("input"));
$("input").onEnter( function() {
$(this).val("Enter key pressed");
});
});
jsfiddle of it here http://jsfiddle.net/VrwgP/30/
It should be well noted that the use of live() in jQuery has been deprecated since version 1.7 and has been removed in jQuery 1.9. Instead, the use of on() is recommended.
I would highly suggest the following methodology for binding, as it solves the following potential challenges:
By binding the event onto document.body and passing $selector as the second argument to on(), elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body rather than $selector directly, which means $selector can be added, removed and added again and will never load the event bound to it.
By calling off() before on(), this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.
By wrapping the script within $(function() {...}), this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready() does not get fired for AJAX requests, while $(function() {...}) does.
Here is an example:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
If your input is search, you also can use on 'search' event. Example
<input type="search" placeholder="Search" id="searchTextBox">
.
$("#searchPostTextBox").on('search', function () {
alert("search value: "+$(this).val());
});
//Short and simple solution
$(document).ready(function(){
$('#TextboxId').keydown(function(event){
if (event.which == 13){
//body or action to be performed
}
});
});
HTML Code:-
<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />
<input type="button" id="btnclick">
Java Script Code
function AddKeyPress(e) {
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13) {
document.getElementById('btnEmail').click();
return false;
}
return true;
}
Your Form do not have Default Submit Button
Another subtle variation.
I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:
(function($) { $.fn.catchEnter = function(sel) {
return this.each(function() {
$(this).on('keyup',sel,function(e){
if(e.keyCode == 13)
$(this).trigger("enterkey");
})
});
};
})(jQuery);
And then in use:
$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });
This variation allows you to use event delegation (to bind to elements you haven't created yet).
$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });
I could not get the keypress event to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:
"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)
I had to use the keyup or keydown event to catch a press of the enter button.
<form name="searchForm" id="searchForm" onsubmit="doSomething(event)">
<input type="text" name="search" id="search">
</form>
<script>
function doSomething(event){
let $val = $('form#searchForm input[name="search"]').val();
console.log($val);
event.preventDefault();
}
</script>
One simple way it can be done in this way. Enter text or number, hit enter key and get the entered input value.