I'm not really sure if I'm phrasing this correctly, but what I'm trying to do is have a function return a div's id on a keydown event.
Say my HTML is:
<div class="pad" id="snare" data-key="97"></div>
<div class="pad" id="kick" data-key="98"></div>
Essentially I want my JS to do something like this:
function handlekeydown(e) {
console.log("data-key: " + e.keyCode);
if (e.keycode == $(".pad").data("key")) {
return this.id
}
}
I could write a switch statement with each keycode returning a variable with the same name as the id, but that would defeat the purpose of having it in my HTML.
How would I write a function to search a div for a data-key that would match the keycode and then return its id?
As per the question
How would I write a function to search a div for a data-key that would match the keycode?
You can do it by:
function handlekeydown(e) {
var id;
var element = $('[data-key="' + e.keyCode + '"]');
if (element.length) {
id = element[0].id;
}
}
But as mentioned above you can't return the id from the handler, you might wanna call a method from the event handler which uses id.
function processId(id) {
console.log(id);
}
function handlekeydown(e) {
var element = $('[data-key="' + e.keyCode + '"]');
if (element.length) {
processId(element[0].id);
}
}
A keydown event is a keyboard event.
A keydown event will only trigger on the currently activeElement of the document.
You need a completely different approach - on which I will come forth with a solution proposal if you decide to change your current approach with something that might actually work for a change.
p.s.: I will update this same reply.
Related
Note: I am quite new to javascript so, apologies if this seems trivial.
I have some code that adds a new container to an existing one on the click of a mouse button.
Using the .click() function, a new class is added, then resized and finally, appended to the parent container.
Is there a way for this also to be done with the 'enter' key?
C.prototype.addSolutionContainerTo = function ($container) {
var self = this;
self.$solutionContainer = $('<div/>', {
'class': 'h5p-guess-answer-solution-container',
}).click(function () {
$(this).addClass('h5p-guess-answer-showing-solution').html(self.params.solutionText);
self.trigger('resize');
}).appendTo($container);
};
return C;
})
One solution I have found is something along the lines of:
$(this).keypress(function (event) {
if (event.keyCode === 13) {
$(this).addClass('h5p-guess-answer-showing-solution').html(this.params.solutionText);
self.trigger('resize');
}
});
However, it doesn't seem to work and won't even throw a console log.
Assuming you want the enter key to work no matter what element is "focused" on the page, you might consider attaching the keypress event to the document, like this:
$(document).keypress(function(event){
if (event.keyCode === 13) $button.click();
});
I am trying to get it so that when I press enter while focused on an input, it alerts something.
I have an input tag,
<input></input>
Then I have javascript,
document.getElementsByTagName("input").keyup = function(e) {
if (e.keyCode == 13) {
alert("1111");
}
};
Why is this not working? Here is my codepen: http://codepen.io/darkfyi/pen/meBdzZ.
There are two problems with your code:
The document.getElementsByTagName method returns a HTMLCollection, so you must iterate through this collection, or use the first item by using [0].
If you want to delegate the event keyup by its property, you should use .onkeyup = function() {, as there is no HTMLInputElement.keyup method. You would use keyup in addEventListener method, for example.
So, your code should be something like:
document.getElementsByTagName("input")[0].onkeyup = function(e) {
if (e.keyCode == 13) {
alert("1111");
}
};
Updated codepen.
I've got the following bit of code (using JQuery) that I've written for a project. The idea is to have a function that you can attach to an element within an "item" div and it will return the id of that div. In this case, the div id would be item-[some item primary key value]. This function works probably 9/10 times, but every once in a while it will get to the else else case and return false. I've verified through the console that the input for selector is the exact same JQuery $() item in both the success and fail cases.
I'm relatively new to JavaScript, so there may be something obvious I'm missing, but this is some really unusual behavior.
var recursionCounter = 0;
function getElementID(selector, recursionDepth, searchString){
console.log(selector);
var elementID = selector.attr("id");
if(elementID === undefined){
elementID = "";
}
if(elementID.indexOf(searchString) !== -1){
elementID = elementID.split("-")[1];
return elementID;
} else {
if(recursionCounter < recursionDepth){
recursionCounter++;
return getElementID(selector.parent(), recursionDepth, searchString);
} else {
recursionCounter = 0;
alert("The element clicked does not have an associated key.");
return false;
}
}
}
Here is an example of code that calls this function, for some context.
$(document).on("click", ".edit-pencil-item", function(event) {
//Use helper function to get the id of the surrounding div then pass it to the function
var itemID = getElementID($(this), 10, "item-");
jsEditItem(itemID);
return false;
});
Thanks in advance for any help!
If you want to get the encapsulating element of your clicked element, and you know it should have an id starting with "item-" you should be able to do something along the lines of
$(this).closest('[id^="item-"]').attr('id')
Which says find this elements closest parent that has an id starting with "item-" and tell me its id.
So this is just a small personal project that I'm working on using awesomium in .net. So in awesomium I have this browser open and all that and I want to click this button that has this code.
<a class="buttonright" > Bump </a>
But considering it's a class and not a button I'm having trouble finding a way to "click" it. My plan is to use javascript in awesomium to click it but maybe I'm approaching this from the wrong direction?
Thanks
Update:
After a lot of comments (back and forth) I set up a fiddle, with a working version of this code (the code here works, too, but needed some debugging). The eventTrigger function in the fiddle has been stripped of all comments, but I've added an example usage of this function, which is generously sprinkled with comments.
Browse through it, fork it, play around and get familiar with the code and concepts used there. Have fun:
Here's the fiddle
If by "finding a way to click it" you mean: how to programmatically click this anchor element, then this is what you can use:
Here's a X-browser, slightly verbose yet comprehensive approach:
var eventTrigger = function(node, event)
{
var e, eClass,
doc = node.ownerDocument || (node.nodeType === (document.DOCUMENT_NODE || 9) ? node : document);
//after checking John Resig's Pro JavaScript Techniques
//the statement above is best written with an explicit 9
//Given the fact that IE doesn't do document.<NODE_CONSTANT>:
//doc = node.ownerDocument || (node.nodeType === 9 ? node : document);
if (node.dispatchEvent)
{//dispatchEvent method is present, we have an OK browser
if (event === 'click' || event.indexOf('mouse') >= 0)
eClass = 'MouseEvents';//clik, mouseup & mousedown are MouseEvents
else
eClass = 'HTMLEvents';//change, focus, blur... => HTMLEvents
//now create an event object of the corresponding class
e = doc.createEvent(eClass);
//initialize it, if it's a change event, don't let it bubble
//change events don't bubble in IE<9, but most browsers do
//e.initEvent(event, true, true); would be valid, though not standard
e.initEvent(event, !(event === 'change'), true);
//optional, non-standard -> a flag for internal use in your code
e.synthetic = true;//mark event as synthetic
//dispatch event to given node
node.dispatchEvent(e, true);
//return here, to avoid else branch
return true;
}
if (node.fireEvent)
{//old IE's use fireEvent method, its API is simpler, and less powerful
//a standard event, IE events do not contain event-specific details
e = doc.createEventObject();
//same as before: optional, non-standard (but then IE never was :-P)
e.synthetic = true;
//~same as dispatchEvent, but event name preceded by "on"
node.fireEvent('on' + event, e);
return true;//end IE
}
//last-resort fallback -> trigger any directly bound handler manually
//alternatively throw Error!
event = 'on' + event;
//use bracket notation, to use event's value, and invoke
return node[event]();//invoke "onclick"
};
In your case, you can use this function by querying the DOM for that particular element, like so:
var elem = document.querySelector('.buttonright');//IE8 and up, will only select 1 element
//document.querySelectorAll('.buttonright'); returns a nodelist (array-like object) with all elements that have this class
eventTrigger(elem, 'click');
That should have the effect of clicking the anchor element
If you're looking for a way to handle click events on this element (an anchor that has a buttonright class), then a simple event listener is all you need:
document.body.addEventListener('click', function(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
if (target.tagName.toLowerCase() === 'a' && target.className.match(/\bbuttonright\b/))
{//clicked element was a link, with the buttonright class
alert('You clicked a button/link thingy');
}
}, false);
That's the cleanest way to do things (one event listener handles all click events). Of course, you can bind the handler to specific elements, too:
var buttons = document.querySelectorAll('.buttonright'),
handler = function(e)
{
alert('Clicked!');
};
for (var i=0;i<buttons.length;++i)
{
buttons[i].addEventListener('click',handler, false);
}
Depending on how you want to handle the event, there are numerous roads you can take.
The simplest one is this :
<script type="text/javascript">
function buttonRight_onclick(event, sender)
{
alert("HEY YOU CLICKED ME!");
}
</script>
<a class="buttonright" click="buttonRight_onclick(event, this)">
whereas if you were using a framework like jQuery, you could do it like this:
<script type="text/javascript">
$(document).ready(function() {
$(".buttonright").on("click", function(event) {
alert("HEY YOU CLICKED ME!");
});
});
</script>
<a class="buttonright" >Bump</a>
<a class="buttonright" >Also bump</a>
<script type="text/javascript">
function Button_onclick(event, sender)
{
alert("Button Clicked!");
}
</script>
<a class="Button" click="Button_onclick(event, this)">
I want to add a autocomplete function to a site and found this guide which uses some js code which works really nice for one textbox: http://www.sks.com.np/article/9/ajax-autocomplete-using-php-mysql.html
However when trying to add multiple autocompletes only the last tetbox will work since it is the last one set.
Here is the function that sets the variables for the js script
function setAutoComplete(field_id, results_id, get_url)
{
// initialize vars
acSearchId = "#" + field_id;
acResultsId = "#" + results_id;
acURL = get_url;
// create the results div
$("#auto").append('<div id="' + results_id + '"></div>');
// register mostly used vars
acSearchField = $(acSearchId);
acResultsDiv = $(acResultsId);
// reposition div
repositionResultsDiv();
// on blur listener
acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });
// on key up listener
acSearchField.keyup(function (e) {
// get keyCode (window.event is for IE)
var keyCode = e.keyCode || window.event.keyCode;
var lastVal = acSearchField.val();
// check an treat up and down arrows
if(updownArrow(keyCode)){
return;
}
// check for an ENTER or ESC
if(keyCode == 13 || keyCode == 27){
clearAutoComplete();
return;
}
// if is text, call with delay
setTimeout(function () {autoComplete(lastVal)}, acDelay);
});
}
For one textbox I can call the function like this
$(function(){
setAutoComplete("field", "fieldSuggest", "/functions/autocomplete.php?part=");
});
However when using multiple textboxes I am unsure how I should go about doing this, here is something I did try but it did not work
$('#f1').focus(function (e) {
setAutoComplete("f1", "fSuggest1", "/functions/autocomplete.php?q1=");
}
$('#f2').focus(function (e) {
setAutoComplete("f2", "fSuggest2", "/functions/autocomplete.php?q2=");
}
Thanks for your help.
You should be using classes to make your function work in more than one element on the same page. Just drop the fixed ID's and do a forEach to target every single element with that class.