Javascript click event on anchor not working - javascript

I was trying to call the click event when hitting spacebar on keyboard on an anchor like so.
$("a").on("keypress", function (e) {
if (e.which === 32) {
$(this).click();
e.preventDefault();
}
}
This does not work however. I finally figured out a fix but I don't understand why it works. The simple fix was changing $(this).click() to $(this)[0].click()
What is the [0] doing and how is it making the click event work on the anchor?
Note: I also tried $(this).trigger("click") with no luck either.

See Roman Starkov's answer in the following link:
Jquery how to trigger click event on href element
The native DOM method does the right thing:
$('.cssbuttongo')[0].click();
^
Important!
This works regardless of whether the href is a URL, a fragment (e.g.
#blah) or even a javascript:.
Note that this calls the DOM click method instead of the jQuery click
method (which is very incomplete and completely ignores href).
So basically when you use the indexer you'll access the DOM's native click method instead of the jQuery implementation which does not work for links.
I wanted to mark this topic as duplicated but first I linked a wrong topic so I retracted the flag and now I cannot mark it again. So if someone has the power feel free to mark it as the duplicate of the linked topic. And if this answer helped upvote Roman Starkov's original answer in the link, he deserves it.

I didn't understanda exactly the scenario but that works for me, please try this:
$('a').click(function() {
alert('click...!');
});
//press enter on text area..
$('a').keypress(function(e) {
var key = e.which;
console.log('checking press key: ' + key)
if (key == 32) // the enter key code
{
$('a').click();
}
});
Feel free to rearrange...hope it helps!

Related

JQuery is not triggering atbar button

I am working on a large project and need to fix some accessibility issues.
These is a section which has been generated by https://www.atbar.org/ in a JS format I am not familiar with. The user clicks buttons to change font size, background colour and other html elements to assist them with reading content.
When you click on the buttons with your mouse they work fine. This is an example of how the buttons appear:
<li class=“access-button">
<a title="Decrease Text Size" id="block_accessibility_dec" tabindex=“0">A-</a>
</li>
If I focus my Chrome inspector on the link element I can see there is an event listening for my click:
This appears to trigger the change in font size. I found the code that triggers this click, it is in a JS format that I am not familiar with:
M.block_accessibility = {
init: function(Y, autoload_atbar, instance_id) {
this.defaultsize = M.block_accessibility.DEFAULT_FONTSIZE;
// This event triggers after clicking
Y.all('#block_accessibility_textresize a').on('click', function(e) {
if (!e.target.hasClass('disabled')) {
M.block_accessibility.changesize(e.target);
}
});
// This is the function it runs, it has many cases for all the different buttons.
changesize: function(button) {
Y = this.Y;
switch (button.get('id')) {
case "block_accessibility_dec":
Obviously this is just snippets of the code with comments I added.
What I require is the user to be able to change the font size using just tab and enter, so I added the following JQuery:
$("#block_accessibility_dec").keyup(function(event) {
if (event.keyCode === 13) {
$('#block_accessibility_textresize #block_accessibility_dec').click();
}
});
This is not triggering the change in font size. Yet when I click on the button it does? There is probably a really simple solution here but I've been stuck for ages. I tested the .click() on other elements on the screen and it works for them so the JS is definitely executing.
I have also tested:
$(this).click();
But to no avail.
Try to trigger the click event by the native way:
$('#block_accessibility_textresize #block_accessibility_dec')[0].click();
Source: I tried their demo page together with the chrome inspector and couldn't get the click working with JQuery.
But with the native click event it suddenly worked.
Unfortunately I can't really explain to you, why JQuery doesn't work here. Maybe something with their version (1.11)?
Replace your code with the following code and add the keyup event. This should work when you press the enter key.
Y.all('#block_accessibility_textresize a').on('click keyup', function(e) {
if (e.keyCode == 13 || e.keyCode ==9) {
if (!e.target.hasClass('disabled')) {
M.block_accessibility.changesize(e.target);
}
}
});
You should use the following Jquery:
$('#block_accessibility_textresize #block_accessibility_dec').trigger("click");
Please let me know if this doesn't work.

VueJS - How to detect Ctrl+V?

I've already seen the answers to this question, but it's not the solution I need, since it's for jQuery, and I need something for vue.js.
So far, I was able to detect single character presses using the ff. code:
export default {
name: 'game',
data () {
return {
allowInput: false,
disabledKeys: ['ArrowLeft', 'Home', 'Control']
}
},
methods: {
keymonitor: function (event) {
console.log(event.key)
if (this.disabledKeys.indexOf(event.key) >= 0) {
event.preventDefault()
this.allowInput = false
// alert('not allowed')
} else {
this.allowInput = true
}
},
checkAnswer () {
if (! this.allowInput) {
alert('the key(s) you pressed is/are not allowed')
}
} /* END checkAnswer */
} /* END methods */
} /* END export default */
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.2/vue.min.js"></script>
<input id="typeBox" ref="typeBox" autocomplete="off" placeholder="Type here..."
#keydown="keymonitor" #keyup="checkAnswer()" />
The code above successfully prevents the textbox from accepting ArrowLeft, Home, and Control key presses.
The problem:
I'm trying to figure out how to detect Ctrl+V, because I want to prevent paste action in my text box. Does anyone know how to do this? Thanks in advance.
To detect two keys, Vue provides modifier keys, For example to detect Alt+C, you can simply do:
<input #keyup.alt.67="YourFn">
Similarly for Ctrl+V, you can do:
<input #keyup.ctrl.76="YourFn">
As I can see here, ASCII code for Ctrl+v is 22, so you should be simply able to do :
<input #keyup.22="YourFn">
you can check the js fiddle link for the same
keyup: function(event){
if(event.keyCode == 86 && event.ctrlKey){
// do something here
}
}
https://jsfiddle.net/neelkansara28/wh61rby8/16/
I'm a little late to the party here but for anyone coming here with this same question, there is really no need for anything fancy that is not built into Vue itself. If you don't want to read through all of this
Here is a sandbox with a working example to play with
As the accepted answer says, vue has it's own event listeners as documented here
It also does not require key codes, specifically, to work. So in your case, it will accept the letter v
Below is an example of a vuetify component (although this will work with pretty much any element):
<v-text-field
v-model="textField"
#keydown.prevent.ctrl.v=""
#keydown.prevent.meta.v=""
#click.prevent.right.exact=""
/>
Here is the breakdown of the #stuff that you see there:
To prevent key combos like ctrl/cmd + v:
In the case of combos, in order to make it work, you'll have to listen to keydown instead of the alternatives
To account for Windows, you'll need to use #keydown.prevent.ctrl.v=""
To account for Mac, you'll need to use #keydown.prevent.meta.v=""
#keydown listens for the keydown event
.prevent automatically applies event.preventDefault()
.ctrl/.meta are the modifier keys you're listening for
the meta key is the CMD key on Mac and Windows key on Windows
v is, of course, the other key we are listening for
the empty "" just means we're not giving it a function to run. if you want to do anything additional, you can just simply reference a function here. like: #keydown.prevent.meta.v="doSomethingElse"
If you also want to prevent the right-click (context) menu: #click.prevent.right.exact=""
#click will listen to the click event.
.right is the modifier to listen for right-clicks only
.exact makes sure that no other modifiers are accepted. Without this, someone could press shift + right-click and the context menu would appear as normal. In this case, .exact makes sure we're doing something on any version of right-click

Shortcut keys for Javascript game GUI

I've been making a simple javascript based OOP text game that uses string replacement and variable adjustments tied to button .onclick events. I've been asked to add hotkeys for easier access, and I've been struggling with how to do it.
First I tried using the JSQuery hotkeys script and the .bind command, but that seemed like it would be very time consuming as I'd have to recode every .onclick as a hotkey, and even with unbind, it was firing off every event tied to the key on the script.
I feel like the best way to do would be if I could code the keys to the gui, i.e. if when you pressed "1", it activated the .onclick of button 1, that way the hotkey would be static (except when the button is disabled), but I've no idea how to do that. I've just been using html buttons, (i.e. input type="button" value="" disabled="disabled" id="button1"), I suspect I'd need something more sophisticated?
Thanks in advance for any help, google has been useless.
[EDIT - General description of code]
The way the game works is very simple, via the calling of functions as new events with different text/buttons (and different onclick events tied to those buttons). As an example, the start screen code is:
function startScreen() {
$(document).ready(function () {
$('#text').html("Game title and info");
$('#button1').val("Start Game");
$('#button1').attr("disabled", false);
$("#button1").one("click", function () {
textClear();
buttonClear();
nameScreen();
});
$("#button2").val("Load Game");
$('#button2').attr("disabled", false);
$("#button2").one("click", function () {
textClear();
buttonClear();
loadData();
});
$("#button6").val("Settings");
$('#button6').attr("disabled", false);
$("#button6").one("click", function () {
textClear();
buttonClear();
settingsScreen();
});
});
}
Since the code executed by button one changes between functions, what the hotkey does as well, which was my problem with using the JQuery library code.
When a key is pressed then the event onkeypress is fired. This event provides some values like:
keyCode
charCode
which
So you could do something like:
window.onkeypress = function (event) {
// the keyCode value for the key 1 is 49, for the key 2 is 50
if (event.keyCode == 49) {
// execute the same code as clicking the button 1
console.log("The key 1 was pressed.");
} else if (event.keyCode == 50) {
// execute the same code as clicking the button 2
console.log("The key 2 was pressed.");
}
};
Now, when a user visits your website he could press the keys 1 or 2 on the keyboard and fire the same logic as clicking the buttons "1" and "2" (being something like <input id="button1">) with the left mouse taste.
If you have really a lot of hotkeys then this would be also tedious to type, but without knowing your code I can hardly give you a complete solution. I hope my answer can give you some idea how to proceed further.
EDIT:
Further reading on the topic:
http://unixpapa.com/js/key.html

Cannot get enter keypress to work in jQuery when calling click function

I'm currently working on code that builds a div box when the user clicks on the .pTile div that does not have the .join class. The click function works, however, for accessibility reasons, I need to have the enter key also build the div when the user uses the enter key. There are multiple .pTile's on the page and more or less can be added at any time through a database. I can't seem to get the enter key function to work. Assistance would be much appreciated.
The following is the working click function the code in it is omitted as it's pretty long:
$(document).on('click', '.pTile:not(.join)', function (e) {
//Do stuff
});
This is the code that I am not able to get to work:
$('.pTile:not(.join)').bind('keypress', function (e) {
if (e.keyCode || e.which) {
$('.pTile:not(.join)').click();
return false; }
});
EDIT: I'd also like to note that the key press function does not get fired at all.
Here is a JSBin with a solution: http://jsbin.com/yelomunafo/1/
Basically you add keypress to the $(document).on('click') part.

JQuery - What method can I use to get this code to run without clicking

Ok this example code contains a button. Forget about the button, it does not exist, cannot be referenced and cannot be edited.
The buttons dont exist in this example - they merely represent another process. However the fields still need to be updated from values. Sorry I couldn't explain it better.
Answer:
http://jsfiddle.net/piezack/X8D4M/56/
If you want the event to fire whenever the text inside the box changes, then I think you're best off using jquery's keyup event instead of blur:
$('#FormCustomObject6Name').keyup(
function()
{
var x = $('#FormCustomObject6Id').val();
$("a[href*='http://www.msn.com']").attr('href',('http://www.google.com/search?q='+ x));
$('a#link').text('Link has been updated');
}
);
The only problem with this is that it won't catch instances where users enter data without using their keyboard (paste via right click, etc.).
You could use a mouseover event, say over the button or the link.
I changed this
$('.butter').mouseover(function(){
to have a mouseover the button.
Example: http://jsfiddle.net/X8D4M/39/
You can trigger events on objects yourself manually by using trigger(event).
So this might work for you:
$('button.butter').trigger('click');
Did you try just triggering a click?
$('button.butter').click();
Here's what you're looking for.
$('#FormCustomObject6Name').trigger('blur');
Okay, this is probably not the most efficient solution, but if you use setInterval to check for the changed value you're guaranteed to cover all sources of the change.
setInterval(function(){
var id = $('#FormCustomObject6Id').val();
var name = x + $('#FormCustomObject6Name').val();
if (id.length > 0 && name.length > 0){
$("a[href*='http://www.msn.com']").attr('href',('http://www.google.com/search?q='+ id));
$('a#link').text('Link has been updated');
}
},500);

Categories

Resources