I have got this html. So, i want what CreateWorld calles once. I think this is may do with JQuery function, such as disable(). But i don't know which.
<input type="button" value="Создать мир" onclick="CreateWorld()" class="create_button"/>
I need the button to fire the first time just click on it. I can create a counter. But I think there are any simple solutions. But I do not know what
Thanks!
If you're using jQuery, and want this function to be called once:
$('.create_button').one('click',function(){
CreateWorld();
});
JS Fiddle demo.
The above will allow the event handler to fire once.
Or:
$('.create_button').click(function(){
CreateWorld;
$(this).prop('disabled',true);
});
JS Fiddle demo.
This will allow the button to have a click handler to be assigned for every click but will, after it's been clicked once, disable the button (preventing it from receiving clicks/user interaction).
To use plain JavaScript (albeit requiring a standards-compliant browser):
function buttonActions (){
CreateWorld();
this.disabled = true;
}
document.querySelector('.create_button').addEventListener('click', buttonActions);
JS Fiddle demo.
References:
('Plain') JavaScript:
addEventListener().
document.querySelector().
jQuery:
click().
prop().
one().
You can use jQuery .one() it will only listen click event once
HTML :
<input type="button" value="Создать мир" class="create_button"/>
JQUERY :
$('input.create_button').one('click',CreateWorld);
Try
$('.create_button').on('click',function(){
CreateWorld();
$(this).attr('disabled','disabled');
});
$('.create_button').on('click',function(){
if($(this).hasClass('disabled')) return;
CreateWorld();
$(this).addClass('disabled');
});
So later if you are making ajax call u can remove class to make button to work
onSuccess : $('.create_button').removeClass('disabled');
onFaulure : $('.create_button').removeClass('disabled');
Related
I try to replace an onclick event with other onclick event with javascript:
<button id='myButton' onClick=""/>
OLD onClick event :
$('#myButton').click(function(){
alert('1');
});
and then i do the same like that and change the value of alert , i do like this :
$('#myButton').click(function(){
alert('2');
});
The result of method above is alert show twice for 1 and 2. What i
want is only 2 that must show (i replace alert('1') with alert('2');
not add another alert. How to fix my code?
Try this one:
$(document).off('click', '#myButton').on('click', '#myButton', function(){
alert('2');
});
It will unbind previous event listener and add the new one.
You have 2 jQuery event listeners which listen same element. They know about element's id and this is enough for they work.
What I'm trying to say, that they don't care about onClick
You should code two JS functions, but not jQuery event listeners.
<button id='id' onClick="choose function"/>
function myFunction1() {
//your code
}
function myFunction2() {
//same
}
Finally the problem has been solved. I use method unbind like explain from here :
http://api.jquery.com/unbind/
For my case :
$('#myButton').unbind("click");
Thank you.
Please run this sample in Google Chrome browser.
Stack Snippet
$(function() {
$(":input").select(function() {
$("div").text("Something was selected").show().fadeOut(1000);
alert("Selected");
});
$("button").click(function() {
$(":input").select();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button>Click To Select</button>
<input type="text" value="Some text">
<div></div>
Here why jQuery select event listener is triggering multiple times? Does anyone know the reason behind this? And is there any workaround solution for this without using timeout?
The $(":input") selector is selecting the button too, so it causes recursion. Either use just $("input"), or $(":input:not(button)").
I noticed when the three events are fired, the first doesn't have originalEvent property, so we definitely can dismiss it, and the second two has very similar (however not identical) timestamp. You can store the last timestamp in some variable and in event listener compare it with the event's timestamp. If the rounded values of these two are the same, you can dismiss this event.
$(function() {
var lastTimeStamp;
$("input").select(function(event) {
if (!event.originalEvent ||
lastTimeStamp === Math.round(event.timeStamp)) return;
lastTimeStamp = Math.round(event.timeStamp);
$("div").text("Something was selected").show().fadeOut(1000);
alert("Selected");
});
$("button").click(function() {
$("input").select();
});
});
See updated JS Fiddle.
It appears the issue is a combination of:
the :input selector gets the input and the button, hence multiple events triggered.
even when using just input as the selector there is some odd event propagation being triggered on related elements which is raising the select event handler multiple times.
To avoid both of the above, use input as the selector and also use preventDefault() in the event handler. stopPropagation() may also be required, depending on your HTML stucture.
$(function() {
$('input').select(function(e) {
// e.stopPropagation(); // optional
e.preventDefault();
$('#message').text("Something was selected").show().fadeOut(1000);
console.log('Selected');
});
$('button').click(function() {
$('input').select();
});
});
Working example
UPDATE: We were all fooled. The select() function needs a prevent default.
Rory McCrossan figured it out. Well done mate.
Incidentally, I'm not sure what the benefit of select() actually is! Something like focus() or on('focus',) might make more sense. Not Sure what the context is however. The below still follows:
Why waste time using generalised tag/type selectors which may change? Use an ID, and pick out only the one you want.
If you want to detect multiple, use a class. If you want to use multiple, but figure out which one you clicked, use a class and an ID. Bind with the class, and identify using $this.attr('id').
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button>Click To Select</button>
<input type="text" value="Some text" id="pick-me">
<div></div>
$(function() {
$("#pick-me").select(function(event) {
event.preventDefault();
$("div").text("Something was selected").show().fadeOut(1000);
alert("Selected");
});
$("button").click(function() {
$("#pick-me").select();
});
});
I'm working with a wordpress theme and I need to activate a button when the page loads, but none of the following has worked for me (my button has the ID "reset"):
$(document).ready(function() {
$("#reset")[0].click();
});
--
$(document).ready(function(){
$("#reset").click();
})
--
$(window).load(function(){
$('#reset').click();
});
I put the code in the header or in the page where i need to activate the button, but does not work.
Thanks!
I give you example here
$(document).ready(function(){
$("#reset").click();
})
the code above should work.
JavaScript does not allow seamless programmatic triggering of an actual click event.
What you could do is
declare the click callback as a separate, named function
e.g.
function myClickCallback(e) {
// Do stuff here
}
Set this as the click callback of your button (e.g. $('#reset').on('click', myClickCallback)).
Invoke the callback when the page loads (e.g. $(document).ready(myClickCallback);)
I am not sure why you 'd want this functionality, since it sounds weird. From reading your description, by "activating", you could also mean enabling the button. To do that you should do something like the following
$(document).on('ready', function (e){
$('#reset').removeAttr('disabled');
});
You may need to refer to it using jQuery instead of $:
The jQuery library included with WordPress is set to the noConflict() mode...
https://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers
$(document).ready(function(){
$("#reset").trigger('click');
});
Use the function Trigger with the event click
$(document).ready(function(){
$("#reset").trigger('click');
});
This what works for me:
$(function () {
$('#btnUpdatePosition').click();
});
On the button event, the JQuery binding event doesn't work:
$('#btnUpdatePosition').click(function () {
alert('test again');
});
But it works when I added the event on attribute declaration:
<input type="button" value="Update" id="btnUpdatePosition" onclick="alert('Click has been called')" />
You can also call if you have a function on element:
<input type="button" value="Update" id="btnUpdatePosition" onclick="fncShow();" />
Trying to figure out proper way to make a click event not fire on the icon of a disabled link. The problem is when you click the Icon, it triggers the click event. I need the selector to include child objects(I think) so that clicking them triggers the event whenever the link is enabled, but it needs to exclude the children when the parent is disabled.
Links get disabled attribute set dynamically AFTER page load. That's why I'm using .on
Demo here:(New link, forgot to set link to disabled)
http://jsfiddle.net/f5Ytj/9/
<div class="container">
<div class="hero-unit">
<h1>Bootstrap jsFiddle Skeleton</h1>
<p>Fork this fiddle to test your Bootstrap stuff.</p>
<p>
<a class="btn" disabled>
<i class="icon-file"></i>
Test
</a>
</p>
</div>
</diV>
$('.btn').on('click', ':not([disabled])', function () { alert("test"); });
Update:
I feel like I'm not using .on right, because it doesn't take the $('.btn') into account, only searching child events. So I find myself doing things like $('someParentElement').on or $('body').on, one being more difficult to maintain because it assumes the elements appear in a certain context(someone moves the link and now the javascript breaks) and the second method I think is inefficient.
Here is a second example that works properly in both enabled/disabled scenarios, but I feel like having to first select the parent element is really bad, because the event will break if someone rearranges the page layout:
http://jsfiddle.net/f5Ytj/32/
Don't use event delegation if you only want to listen for clicks on the .btn element itself:
$('.btn').on('click', function() {
if (!this.hasAttribute("disabled"))
alert("test");
});
If you'd use event delegation, the button would need to be the matching element:
$(someParent).on('click', '.btn:not([disabled])', function(e) {
alert('test!!');
});
Demo
Or use a true button, which can really be disabled:
<button class="btn" [disabled]><span class="file-icon" /> Test</button>
Demo, disabled.
Here, no click event will fire at all when disabled, because it's a proper form element instead of a simple anchor. Just use
$('.btn').on('click', function() {
if (!this.disabled) // check actually not needed
this.diabled = true;
var that = this;
// async action:
setTimeout(function() {
that.disabled = false;
}, 1000);
});
.on('click', ':not([disabled])'
^ This means that, since the icon is a child of the button ".btn", and it is not disabled, the function will execute.
Either disable the icon, also, or apply the event listener only to the <a> tag that is your button, or use e.stopPropagation();
I would suggest using e.stopPropagation();, this should prevent the icon from responding to the click.
That doesn't seem to work for me ^
Disabling the icon, however, does.
I would prefer to add the event using delegation here as you are trying to base the event based on the attributes of the element.
You can add a check condition to see if you want to run the code or not.
$('.container').on('click', '.btn', function() {
if( $(this).attr('disabled') !== 'disabled'){
alert('test!!');
}
});
Check Fiddle
You're not using the selector properly.
$('.btn').not('[disabled]').on('click', function () {
alert("test");
});
See it live here.
Edit:
$('.container').on('click', '.btn:not([disabled])', function () {
alert("test");
});
I think what you need is:
e.stopPropagation();
See: http://api.jquery.com/event.stopPropagation/
Basically something like the following should work
$('.icon-file').on('click', function(event){event.stopPropagation();});
You may want to add some logic to only stop bubbling the event when the button ist disabled.
Update:
not sure, but this selector should work:
$('.btn:disabled .icon-file')
Due to a plugin being used, I can't add the "onClick" attribute to the HTML form inputs like usual.
A plugin is handling the forms part in my site and it doesn't give an option to do this automatically.
Basically I have this input:
<input type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style="">
I want to add an onClick to it with jQuery onload for it to be like this:
<input onClick="myfunction()" type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style="">
How do I go about doing this?
I know this might not be standard practice but seems like the easiest option to do in my situation.
I'm a newbie to jQuery so any help is very much appreciated.
You can use the click event and call your function or move your logic into the handler:
$("#bfCaptchaEntry").click(function(){ myFunction(); });
You can use the click event and set your function as the handler:
$("#bfCaptchaEntry").click(myFunction);
.click()
Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
http://api.jquery.com/click/
You can use the on event bound to "click" and call your function or move your logic into the handler:
$("#bfCaptchaEntry").on("click", function(){ myFunction(); });
You can use the on event bound to "click" and set your function as the handler:
$("#bfCaptchaEntry").on("click", myFunction);
.on()
Attach an event handler function for one or more events to the
selected elements.
http://api.jquery.com/on/
try this approach if you know your object client name ( it is not important that it is Button or TextBox )
$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');
try this ones if you want add onClick event to a server object with JQuery
$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');
Try below approach,
$('#bfCaptchaEntry').on('click', myfunction);
or in case jQuery is not an absolute necessaity then try below,
document.getElementById('bfCaptchaEntry').onclick = myfunction;
However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...
Read more on this post https://stackoverflow.com/a/6348597/297641
$("#bfCaptchaEntry").click(function(){
myFunction();
});
Or you can use an arrow function to define it:
$(document).ready(() => {
$('#bfCaptchaEntry').click(()=>{
});
});
For better browser support:
$(document).ready(function() {
$('#bfCaptchaEntry').click(function (){
});
});
let a = $("<a>bfCaptchaEntry</a>");
a.attr("onClick", "function(" + someParameter+ ")");
as #Selvakumar Arumugam suggested, but the function call on registering also
$('#bfCaptchaEntry').on('click', myfunction);,
rather than use
$('#bfCaptchaEntry').on('click', () => { myfunction});