javascript function execute more times when i click with jquery button - javascript

I try make button with jQuery I call the JavaScript function, but I got problem :
after page loaded, first time click on mybutton there is no reaction
second click will execute function twice
third click will execute function three
and more
Why my code execute many more ? I just want " 1 click 1 execution JavaScript function"
my code like this
<script type="text/javascript" language="javascript">
function showcase(){
var foo = function () {
alert('tutup');
};
$('#create-new').on('click',foo);
return false;
}</script> <button class="button" id="create-new"onclick="return showcase();">show text</button>
please help me out this problem
for try my full error code at here http://jsbin.com/ovucer/1/edit

You are registering multiple click event listeners to the element
Every time you click on the button you are adding a new click handler to the button using showcase method, it is not needed
<button class="button" id="create-new">show text</button>
<script type="text/javascript" language="javascript">
var foo = function () {
alert('tutup');
};
$('#create-new').on('click',foo);
</script>

This happens because you bind a click event, which calls showcase() function, which as well binds a new click event, that calls foo() method. And the last iteration is repeated every time you click the button. This is sort of recursion working here.
The right way will be to bind a click event a single time, after the element is loaded:
<button class="button" id="create-new">show text</button>
<script type="text/javascript">
$("#create-new").on("click", function() {
alert("tutup");
});
</script>

You are registering an onclick function in onclick,
use this:
$('#create-new').on('click', function(){ alert('text button'); return false; });

You're binding the click event twice. Using onclick on the HTML and over again, using jQuery .on().
To make your life easier, and as you're using jQuery already, do it just at the document ready event:
var foo = function () {
alert('text button');
return false;
};
$(function () {
$('#create-new').on('click',foo);
});
And fix your HTML bit, by removing the onclick:
<button class="button" id="create-new">show text</button>

try this in your script tag and delete the onclick event in the button:
var foo = function () {
alert('tutup');
};
$('#create-new').on('click',foo);
return false;

Related

A Function that’s dedicated to adding the event listener to the newly created button

I'm trying to create a function that is dedicated to adding the event listener to the newly created button.
I'm currently taking a course and I can't seem to understand this part:
"Optional (Advanced): You may choose to have another function that’s
dedicated to adding the event listener to the newly created button
rather than including the code inside the addListItem() function. If
you do so, you’ll have to pass two parameters to the new function—the
first is the variable referring to the button (to add the event
listener to it), and the second is the Pokémon object, which is
necessary to call showDetails in the event handler from there.
Finally, call that new function inside addListItem() after the button
is appended to the DOM."
Here is a snippet of what I came up with:
function eventListener(button, pokemon) {
button.addEventListener("click", function () {
showDetails(pokemon);
});
}
I recommend checking out the full code: https://codesandbox.io/s/event-listener-lm16im
All that function is doing is taking reference of a button and data to display, add 'click' event listener on that button and call showDetails() function when that button is clicked.
Here, I have created demo for you to understand how it works
https://jsfiddle.net/6jhmaz8x/1/
HTML file
<html>
<body>
<button id="newButton">
Create new button
</button>
<div id="container">
</div>
</body>
</html>
JS File:
function eventListener(button, pokemon) {
button.addEventListener("click", function () {
showDetails(pokemon);
});
}
function showDetails(pokemon){
console.log(pokemon)
}
window.addEventListener('DOMContentLoaded', (event) => {
document.getElementById('newButton').addEventListener('click',()=>{
let button = document.createElement('button');
button.type = 'button';
button.innerHTML = 'Show details';
document.getElementById('container').appendChild(button)
let pokemon = 'this is pokemon'
eventListener(button,pokemon)
})
});

Function called on second click of button ( not on first )

I have a button when clicked i want it to ensure the .mo function is called, however it will only run that function on the second click.
The mealplan() function is running correctly
HTML
<button class="" id="mealbtn" onclick="mealplan()">CLICK ME</button>
I need both the mealplan() and .mo function to be called upon click.
function mealplan(){
// also runs on click
}
Shopify.mo = function(q,ref) {
// this is the function that I need to run uupon click, but it is only running on second click
};
$('#mealbtn').on('click', function(e) {
// should call the .mo function on click
Shopify.mo(Shopify.queuemeals,"note");
});
The jQuery on('click') method only happens when the button is clicked.
Your code is suggesting that when the button is clicked, we initialize the button's click method.
To fix it, move your jQuery event to a function that runs when the page loads:
$( document ).ready(function() {
$('#mealbtn').on('click', function(e) {
// should call the .mo function on click
Shopify.mo(Shopify.queuemeals,"note");
});
});

How do I call my jQuery function so that it will run in my document.ready function?

In my application I have a script:
<script type="text/javascript">
function pageLoad(sender, args){
$('#nursing').click(function () {
document.getElementById("ddlPositionType").selectedIndex = 1;
$("#btnSearch").click();
a.href = "#";
return false;
});
}
</script>
Then below it I am attempting to call it when the page is loaded like this:
<script type="text/javascript">
$(document).ready(function () {
$('#nursing').click();
});
</script>
This does not fire when the page load as it should and it causes no errors in my console. What is most confusing is that if I took from document to return false from the first code block and placed it where I am trying to call the $('nursing').click(); the code will run like it is supposed to.
As reference #nursing is simply a link used on my slider to control content.
<a id="nursing" class="oslide">Nursing Positions</a>
The code you've written in pageLoad is an instruction to set up a click handler. That setup will not be executed unless the pageLoad function is called prior to your call to click the button in document.ready. The easy fix may be to simply modify your code so that it calls pageLoad, and then clicks the anchor.
<script type="text/javascript">
$(document).ready(function () {
pageLoad();
$('#nursing').click();
});
</script>
But this seems a lot of overkill to call a function by performing a click. Why not just make a function out of the click handler and call that code in document.ready instead? If you still need the click handler, call the function in the click handler.
function onNursingClick() {
document.getElementById("ddlPositionType").selectedIndex = 1;
//... and so on....
}
function pageLoad() {
$("#nursing").click(onNursingClick);
}
$(function() { //shorthand for $(document).ready(...);
onNursingClick();
pageLoad();
})
It's not working because in your document.ready script you're not calling the function pageLoad() that you created earlier. You are firing a click event. So try this:
<script type="text/javascript">
$(function(){ //Jquery shorthand for document.ready
pageLoad(sender, args); //pass in what you need
});
</script>

A simple Unobtrusive JavaScript example

<script>
var el = document.getElementById('btn');
e1.onclick=function()
{
//
alert('hello');
};
</script>
<button type="button" id="btn" >Log-in</button>
I am simply testing how unobstrusive javaScript works with a simple button onclick() event but when i click on the Log-in button nothing happens alert box doesn appears
Your script appears before the button.
It runs before the button is added to the DOM.
document.getElementById('btn') doesn't find the button because the button doesn't exist then.
Move the script after the button or put it in a function and call that function after the button exists (e.g. from the window's load event).
Also, don't rename your variables in the middle of your code. A lower case L and the numeral 1 aren't interchangeable.
The issue is you try to attach the handler before the element exists. <script> tags are executed immediately and so the browser hasn't created the button element at that time.
A solution would be to wrap it in window.onload:
window.onload = function(){
var el = document.getElementById('btn');
e1.onclick=function()
{
//
alert('hello');
};
};
Alternatively you can use the DOMContentLoaded event. This differs from onload because it doesn't wait for images and CSS to be loaded. It isn't supported by IE8 or lower though:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("ready to attach events");
});
yes as said by above 2 answers you can wrap your code in window.onload else you can write a function and call it onclick event of button as shown below
function myfunction() {
alert('Hello');
};
<input type="button" onclick="myfunction()" value="Click Me!" />
http://jsfiddle.net/wf8yJ/13/

jQuery ajax defined actions

When I'm loading some content through ajax it returns an jQuery .click event and some elements. But when the ajax content is loaded a couple of times and I click the the button that is bound to the .click event, the action is executed a couple of times.
For example the ajax content is:
<script type="text/javascript">
$('#click').click(function() { alert('test') });
</script>
<input type="button" id="click" value="click here">
If this is refreshed 5 times and I click the button I will get 5 alert boxes.
Is there a workaround for this?
You can use the unbind function just before the click, something like this:
$('#click').unbind('click').click(function() { alert('test') });
That should let only one function associated with the click
The JQuery one method unbinds the handler after it is invoked:
$('#click').one("click",function() { alert('test') });
More info:
http://docs.jquery.com/Events/one

Categories

Resources