Enter key to append container in javascript - javascript

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();
});

Related

Call function with mouse click

I have a text area. Each time the enter key is entered the cursor travels to the next line of the text area and a function is called. This function posts/updates the entry in a database. I want it so that if I edit a line and then click on the mouse to resume typing at another line the function is again called on the mouse click
$("#textarea").keydown(function (e) {
if (e.keyCode == 13) {
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
e.preventDefault();
stream();
Is it possible to change my line to something like this and the method gets called on pressing the enter key or pressing the mouse(anywhere in the text area)?
if (e.keyCode == 13 || mouse.click) {
I know the above isn't correct but want to illustrate what I'm after
You could take use of jQuery's .on method like so:
$("#textarea").on('click keydown', (e) => {
if(e.keyCode && e.keyCode == 13 || e.type == "click" ){
// Do stuff
}
});
It takes a first parameter as string with different events, which mean you can listen to multiple events at once. The second is a callback function, where you can track the event that is triggered. Nb: Events are different between click and keydown. You can have a closer look by putting console.log(e); in your callback
You'll need to attach another event listener. The keydown event will not trigger when a mouse is clicked. You will need to add a $(...).click(function ...) as well. For example...
function myFunction (e) {
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
stream();
}
$("#textarea").keydown(function() {
if (e.keyCode == 13) {
myFunction()
e.preventDefault();
}
});
$('#textarea').click(myFunction)
Instead of putting a condition you can create 2 events and a common function to handle it.
Foe Example:
$("#textarea").keydown(function (e) {
if (e.keyCode == 13) {
logic1()
$("#textarea").click(function() { logic1();});
function logic1(){
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
e.preventDefault();
stream();
}
I don't know about jQuery but with vanilla JS you can do something like this:
const textarea = document.querySelector('textarea');
const foo = event => {
const output = document.querySelector('output');
output.textContent = event.type;
}
textarea.addEventListener('click', foo, false);
textarea.addEventListener('keypress', foo, false);
<textarea></textarea>
<output></output>

Javascript click a class button

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)">

using a function on textbox focus?

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.

ExtJs simulate TAB on ENTER keypress

I know it is not the smartest idea, but I still have to do it.
Our users want to use ENTER like TAB.
So, the best I came up with is this:
Ext.override(Ext.form.field.Base, {
initComponent: function() {
this.callParent(arguments);
this.on('afterrender', function() {
var me=this;
this.getEl().on('keypress',function (e){
if(e.getKey() == 13) {
me.nextNode().focus();
}
});
});
}
});
But it still does not work exactly the same way as TAB.
I mean, it works OK with input fields, but not other controls.
May be there is some low-level solution.
Any ideas?
In the past I've attached the listener to the document, something like this:
Ext.getDoc().on('keypress', function(event, target) {
// get the form field component
var targetEl = Ext.get(target.id),
fieldEl = targetEl.up('[class*=x-field]') || {},
field = Ext.getCmp(fieldEl.id);
if (
// the ENTER key was pressed...
event.ENTER == event.getKey() &&
// from a form field...
field &&
// which has valid data.
field.isValid()
) {
// get the next form field
var next = field.next('[isFormField]');
// focus the next field if it exists
if (next) {
event.stopEvent();
next.focus();
}
}
});
For Ext.form.field.Text and similar xtypes there is a extra config enableKeyEvents that needs to be set before the keypress/keydown/keyup events fire.
The enableKeyEvents config option needs to be set to true as it's default to false.
ExtJS API Doc
Disclaimer: I'm not an expert on ExtJs.
That said, maybe try something like:
if (e.getKey() === 13) {
me.blur();
return false; // cancel key event to prevent the [Enter] behavior
}
You could try this
if (e.getKey() === 13) {
e.keyCode = Ext.EventObject.TAB
this.fireEvent(e, {// any additional options
});
}
Haven't really tried this ever myself.

only writing "return false" once to handle clicking on many links

Instead of writing return false; many times is there a way to set a collection of links such that if any of them are clicked the click function would return false;? I'd still like to have most links return true so showing code that would return true vs. return false would be particularly appreciated.
The goal is writing less code. I'd also like to know if this is a bad idea for reason I can't understand.
The simpliest method is binding one event listener to the document, and checking for the target: http://jsfiddle.net/gKZ7q/
document.addEventListener('click', function(e) {
if (e.target.nodeName.toUpperCase() === 'A') e.preventDefault();
}, false);
For anchors with nested elements, you have to add an additional loop:
var targ = e.target;
do {
if (targ.nodeName.toUpperCase() === 'A') {
e.preventDefault();
break;
}
} while ((targ = targ.parentNode) !== document.documentElement);
// document.body should be fine. Using document.documentElement in case
// that a fool places an anchor outside the <body>
Links can also be triggered through a key event.

Categories