$.getscript adding duplicate event listeners - javascript

I know whats wrong in code but i am not able to understand why jquery is doing that ,so let me explain my problem with following code
test.html
#############
<!doctype html>
<html class="no-js" lang="en">
<head>
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
</head>
<body>
<div class="wrapper wrapper-layout"> <!-- Header with navigation - Start -->
<button id="btnTestMain" type="button" value="Adjust" class="btn btn-
red1">Button test MAIN</button>
<div id="injectHeaderMainHTML"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#injectHeaderMainHTML").load("/ui-test/test_page.html", 'f' + (Math.random() * 1000000));
$.getScript("js/test1.js", function() {
});
});
</script>
</body>
</html>
###test1.js######
$(document).ready(function() {
$("#btnTestMain").click(function (event) {
$.getScript("/ui-test/js/test.js").done(function() {
console.log("script loaded");
}).fail(function() {
console.log('problem in loading test js');
});
});
}); // Document Ready Closed
test_Page.html
###############################
<button id="btnTest1" type="button" class="btn btn-red1">Button test
1</button>
<button id="btnTest2" type="button" class="btn btn-red1">Button test 2</button>
test.js
###############
function testFunction()
{
console.log("test function called");
}
$(document).ready(function () {
$("#btnTest1").click(function (event) {
console.log("button1 clicked");
});
$("#btnTest2").click(function (event) {
testFunction();
});
});
Now every time i click btnTestMain, it adds event listener to btnTest1 and btnTest2 , so if i click btnTestMain 5 times there will be 5 click event listeners on btnTest1 and 5 on btnTest2.
Can anyone explain why this is happening? I know how to resolve the issue but i am not able to understand reason for duplicate event listeners.

Each time 'test.js' is loaded, jQuery adds the 'click' listener to the two button elements. The key here is that it will not remove any old ones, and that is why you are getting the duplication (which, in reality, isn't a duplication).

Related

JQuery button OnClick not triggering

Hope everybody is having a good day. I had this buton and code, which worked for me.
I also followed the jQuery documentation: https://api.jquery.com/click/
$(function () {
$("#btnName").click(function () {
console.log("test");
});
}
I then upgraded webpack and JQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
If anybody can help me out that would be awesome. Thanks in advance.
Edit: HTML for button:
<!-- NEW CONTACT BUTTON -->
<div class="new-contact-buttons">
<div class="btn-grouped">
<button type="button" class="btn btn-default btn-block bottom" id="btnRetrieveCallerMatches" disabled style="display:none;">Retrieve
caller matches</button>
<button type="button" class="btn btn-default btn-block bottom" id="btnNewContactForm" disabled style="display:none;">New
contact</button>
</div>
</div>
I am now trying this code, but unfortunately its still not working:
$(function () {
$("#btnNewContactForm").click(function () {
console.log("######## clicked new contact")
});
});
I re-enable the button when I need it using:
$("#btnNewContactForm").show();
$("#btnNewContactForm").removeAttr("disabled");
And the button shows up so that piece of code works.
I also checked if the top function is being executed and it is.
Try this :
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<button id="btnName">click me</button>
</body>
<script type="text/javascript">
$(document).ready(function () {
$("#btnName").on("click", function () {
console.log("test");
});
});
</script>
</html>
In each and every one of your examples you are forgetting to close your function, small syntax mistake, but the following code will work
$(function () {
$(document).ready(function() {
$("#btnName").click(function () {
console.log("test");
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnName">Hi</button>
Just before the button code I had a sort method:
$(".phonebook table").tablesorter();
I think because the upgrade (webpack or jquery) this function stopped working and it wouldn't execute any code after this. So the code was fine all along but the binding code wasn't executing. Sorry for wasting everyones time.
When I put this code before the tablesorter everyting worked fine:
$("#btnNewContactForm").click(function () {
console.log("#######" + "saving new contact");
newContact();
});
$(function() {
$(document).on('click', "#btnName.app", function(e) {
e.preventDefault()
console.log("clicked");
});
});
you forgot to put ")" in the end of $(function(){...})

How to attach a click handler with addEventListener

This is the html part of my code:
<!DOCTYPE html>
<html>
<head>
<h>
<title> This page</title>
</h>
</head>
<body>
<button id = "go-button" >GO</button>
<script src="main.js"></script>
</body>
</html>
This is the javaScript part of my code:
function buttonClicked(){
console.log("button clicked");
}
var btn = document.getElementById("go-button");
btn.addEventListener("clicked", buttonClicked);
Whenever i try to print it on console, it does not show any output, i am confused
There is no event clicked but click:
btn.addEventListener("click", buttonClicked);
Correct clicked to click and it should work.
The event name is "click", not "clicked"
The addEventListener function takes two parameters one is the event and second the function to be executed, you have speelled the first parameter wrong.
btn.addEventListener ('click', buttonClicked);

It does not show me any output on console screen. What may be the problem

When I click The button it does not show me any output on the console window
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button type="button" id="Click me">Click me</button>
<script type="text/javascript" src="script.js">
</body>
</html>
->js
var printNumber=document.getElementById('Click me');
printNumber=document.addEventListener('Click',showNo);
function showNo() {
console.log('I was Clicked');
}
You have a few issues with your code.
Firstly you need to close your <script> tag in your HTML:
<script type="text/javascript" src="script.js"></script>
Secondly, your id shouldn't have spaces in it. You can change it to something like btn-click:
<button type="button" id="btn-click">Click me</button>
And then make sure to target it properly in your Javascript:
var printNumber=document.getElementById('btn-click');
Thirdly, your event name should be lowercase (as Javascript is case-sensitive), so change "Click" to "click"
Lastly, you want to add the click event listener to your button, which is stored in the variable printNumber. At the moment you are adding the event listener to your document and not the button. To add it to your button you can use:
printNumber.addEventListener("click", showNo); // add click event listener to button
See working example below:
var printNumber = document.getElementById('btn-click'); // change id selector
printNumber.addEventListener('click', showNo); // change 'Click' to 'click'
function showNo() {
console.log('I was Clicked');
}
<!DOCTYPE html>
<html>
<head>
<title>Awesome button</title>
</head>
<body>
<button type="button" id="btn-click">Click me</button> <!-- change id -->
<script type="text/javascript" src="script.js"></script> <!-- close script -->
</body>
</html>
It should be click not Click!
JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
var printNumber=document.getElementById('Click me');
printNumber=document.addEventListener('click',showNo);
function showNo() {
console.log('I was Clicked');
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button type="button" id="Click me">Click me</button>
</body>
</html>
You had one typo Click which is supposed to be click.
`printNumber=document.addEventListener('Click',showNo);`
^^^^^^^^
you should add event listener to that particular element not to the complete document.
var printNumber=document.getElementById('Click_me');
printNumber.addEventListener('click',showNo);
function showNo() {
console.log('I was Clicked');
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button type="button" id="Click_me">Click me</button>
</body>
</html>

Why wrap JavaScript in this "(function($){ ... JavaScript code ..})(jQuery);"?

I use mvc5. Do not include jQuery in test.
_Layout.cshtml:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title></title>
</head>
<body>
#RenderBody()
</body>
</html>
Test.cshtml:
<script type="javascript/text">
function myFunction() {
alert("its is working");
}
</script>
<button onclick="myFunction()">Click me</button>
In result I have an error: ReferenceError: myFunction is not defined
and the result code:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title></title>
</head>
<body>
<button onclick="myFunction();">Click me</button>
<script type='text/javascript' >
(function($){
function myFunction() {
alert("I am working");
};
})(jQuery);
</script>
</body>
</html>
I have read a lot about this error and have not founded the answer. Could you clarify, who wrap JavaScript code? Is there any flag to cancel it? Is there any other way to resolve the problem?
Something (probably MVC5) is wrapped your code for you, but with good reason. Putting onclick handlers on elements pointing at a globally declared function is how JS was written in the '90s.
To resolve it, put an id attribute on your button and remove the inline event handler:
<button id="mybutton">
and then use jQuery to register the event handler:
$('#mybutton').on('click', function () {
alert("I am working");
});
or, since you mentioned in later comments that you have a loop generating these elements, use a class and a data- attribute instead:
<button class="myclass" data-id="...">
with code:
$('.myclass').on('click', function() {
var id = $(this).data('id');
...
});
<script>
function myFunction() {
alert("its is working");
}
</script>
<button onclick="myFunction()">Click me</button>
This will work. cheers

Redirecting using JS file instead of HTML event handler?

So currently I want to have my javascript in an attached JS file instead of using the 'OnClick' function attached to HTML objects. So far I've got:
<html>
<head>
</head>
<body>
<h1 id = '5' class = ''>6</h1>
<button id = '7' class = ''>8</button>
<script src = 'js/9.js'></script>
</body>
</html>
But unfortunately, I can't quite get the redirect going from clicking the button. It should have this source
document.getElementById('7').onclick = function () {
and then redirecting to a different page. Any tips on how I can improve this?
Please use strings as ID. I know you can now use numbers but it is not recommended
Use the load event handler
You MAY be submitting the page to itself when not giving the button a type so return false or preventDefault
what's with the spacing around = in the attributes? Not necessary nor recommended.
Like this
<html>
<head>
<script src="js/9.js"></script>
</head>
<body>
<h1 id="five" class="">6</h1>
<button id="seven" class="">8</button>
</body>
</html>
where js file has
window.onload=function() {
document.getElementById("seven").onclick = function () {
location.replace("page2.html"); // or just location="page2.html";
return false;
}
}
Using jQuery it would be
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/9.js"></script>
</head>
<body>
<h1 id="five" class="">6</h1>
<button id="seven" class="">8</button>
</body>
</html>
where js file has
$(function() {
$("#seven").on("click",function (e) {
e.preventDefault();
location.replace("page2.html"); // or just location="page2.html";
});
});
LASTLY you do not need script at all:
<form action="page2.html">
<button type="submit" id="seven" class="">8</button>
</form>

Categories

Resources