Button onclick to click() jquery - javascript

I have a button that reacts to onclick() at the moment, but I want it to work with jquery.
$('#nupp1').click(function() {
raiseButtonAction(realPlayer, gameState);
});
raisebuttonaction is in another .js
This piece of code isn't working.
Am I doing something wrong?
edit1:
$(document).ready(function() {
$('#nupp1').click(function() {
raiseButtonAction(realPlayer, gameState);
});
});

Assuming you have this:
<head>
<scripts />
</head>
<body>
<a id="nupp1"></a>
</body>
You code will not work. jQuery will not be able to find the element. The element must exists for that function to work. So
<a id="nupp1"></a>
<script />
Will work because a is being rendered before the script.
You can also use $(document).ready or $() to execute your function when the DOM nodes load.
Or you can use jQuery.live.
jQuery API
ready Specify a function to execute when the DOM is fully loaded.
live Attach a handler to the event for all elements which match the current selector, now and in the future.

Related

anchor tag refresh page

I have a problem with anchor tag i fill my html table with append jQuery and inside a td there is anchor tag when i click on it instead of calling it's function it refresh the page:
$('.show-directions').click(function( event ) {
event.preventDefault();
$('.ui.modal').modal('show');
setTimeout(function() {
initMap();
}, 500);
});
function initMap(){
console.log("initMap has been called.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<a class="show-directions" href="">Detail</a>
Change your code to the following:
$(document).on('click', '.show-directions', function(){
//YourCode
});
And it should work.
For an explanation of the problem, read #Optimus Prime answer's here: Why doesn't click work on appended elements?
I did something else
<a class="show-directions" href="javascript:tacos();" >
and i called the function tacos which has do the same thing
function tacos () {
$('.ui.modal').modal('show');
setTimeout(function() {
initMap();
}, 2000);
}
As you can see (after my edit to your question), assuming you have properly referenced the Bootstrap library, your code is working as it should. Your issue therefore must be with something else on the page.
You've indicated that you are dynamically adding the a element with .append(). In this case, the click event handler is being registered before the element has been added to the document. To ensure that it is handled, use "event delegation", which is the process of setting up the event handler on a higher level element (that exists at the time of the event registration) in the document and then when the event is later initiated by a lower-level element, event bubbling causes it to arrive at the higher element. You then check to see what element initiated the event.
Having said all of this, you should not use an a for this in the first place. <a> elements are for navigation, not for hooks into JavaScript. It is semantically incorrect to use a hyperlink for non-navigational tasks. It will cause problems for users who use assitive technologies (like screen readers) to surf the web, and (as you already know, given your code) requires you to disable the browser's native desire to navigate by adding event.preventDefault().
Instead use some other element to trigger your function, like a span element:
// Intercept the event at the document level, but check to see if
// it originated with an element that has the .show-direcions class
$(document, '.show-directions').click(function( event ) {
$('.ui.modal').modal('show');
setTimeout(function() {
initMap();
}, 500);
});
function initMap(){
console.log("initMap has been called.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<span class="show-directions">Detail</span>
Add this in script $(function(){$("#AnchorTagID").click(function(){return false;});}); or use <button type='button'>Add Anchor Attributes here<button/>
Or instead you can add href="#" instead of empty href or entirely remove it from there.

onClick eventlistener in JS without using onclick function in HTML

I have a html file and js file I want to execute JS when a button is clicked in html. for this I can use onclick event in html but the condition is that I should not modify the HTML file.
I tried to add eventlistener in my JS but that didn't worked.
<p align=center>
<button class="stdbutton" id=button2 name=button2>
Click Me
</button>
</p>
$("button2").click(function() {
alert("button2 clicked");
});
please see the fiddle link for further reference: http://jsfiddle.net/gqpr0g9w/
thanks in advance
Try the FIDDLE,
Basically the first issue with your fiddle was you are using js library other than jquery. Jquery code won't execute without referencing the jquery library.
Secondly you are using an invalid selector,
$("button2")
you can replace this with an id based selector (# selector) as per your markup
$("#button2")
And finally try wrapping the code under jquery closure under document ready event that will ensure that the event will attach when the related object is loaded on the browser.
Finally will becomes
$(document).ready(function() {
$("#button2").click(function() {
alert("button2 clicked");
});
});
Hope it works for you..
Include jQuery in your jsfiddle. Use one of the below to attach an event listener for click using jQuery
$("#button2").on("click", function() {
alert("button 2 clicked");
});
or
$("#button2").click(function() {
alert("button2 clicked");
});
case jQuery is included in the html:
js file -
$("#button2").click(function() {
alert("button2 clicked");
});
// notice the # symbol before the word "button2" representing that we are looking for an ID
case jQuery is NOT included in the html:
<script src="lib/jquery-2.1.4.min.js"></script>
<script src="js/myJavaScript.js"></script>
jQuery script must first be included
and then you can execute the same code as shown above.
Well, you are trying to use jQuery, but there is no jQuery included in your html-File. In fact there is no script included in your html at all like
<script src="lib/jquery-2.1.4.min.js"></script>
<script src="js/myJavaScript.js"></script>
I don't think you will be able to do that without modifying the html-file.

JQuery : Removing DOM objects that have been added in load()

File contents are given below. I have a button, "load_button", whose click event triggers a load() function. The html file loaded with the function contains another button, "my_button". The callback of the load() function adds a handler for the click event of "my_button". The problem is, every time I press "load_button", a new click event handler is added, and the alert in the event handler pops up multiple times. I want to delete previously created "my_button" with its event handler, before creating the new one. What I tried is adding the following command, where its commented out in the file descriptions below.
$('#page').empty();
No luck. I wanted a general solution, since I'll have other DOM objects to be removed. How can I remove them?
Also, it does not work when I replace
$('#page').on('click', '#my_button', function () {
with
$("#my_button").click(function() {
Why isn't it working? Isn't the callback function of load() supposed to be run after the loading is done, and DOM objects are available?
main.html
<html>
<head>
...
<script src="main.js"></script>
</head>
<body>
...
<a id="load_button">Load!</a>
<div id="page">
</div>
</body>
</html>
1.html
<div>
<a id="my_button">Go!</a>
</div>
main.js
$(document).ready(function(){
$('#load_button').click(function() {
// $('#page').empty();
$("#page").load('1.html', load_scripts());
});
});
function load_scripts() {
$.getScript('script.js');
}
script.js
$(document).ready(function(){
$('#page').on('click', '#my_button', function () {
// $("#my_button").click(function() {
alert('COWABUNGA!');
});
});
It looks like you don't need to load scripts dynamically at all. Try a main.js that looks like this:
$(document).ready(function(){
$('#load_button').click(function() {
$("#page").load('1.html');
});
$('#page').on('click', '#my_button', function () {
alert('COWABUNGA!');
});
});

Using jQuery to change the background image

I am trying to change the background image of a link when it get clicked. I keep getting the error that you cannot call 'click' on null.
JQuery (in the header)
<script type="text/javascript">
$('a.upvote-arrow').click(function(){
$('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
});
</script>
HTML
<div class="top-comment-vote">
</div>
Thanks
Try adding $(document).ready:
<script type="text/javascript">
$(document).ready(function(){
$('a.upvote-arrow').click(function(){
$(this).css('background-image','url(../images/icons/up-arrow2.png)');
});
})
</script>
Are you sure this script is being loaded after the html is in the DOM?
Try wrapping what you wrote in a onload closure.
$(function() {
$('a.upvote-arrow').click(function(){
$('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
});
});
Another thing you can do is take advantage of delegation for the event registration.
$('body').on("click", ".a.upvote-arrow", function(){
$('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
});
This binds it to the body instead.
Try wrapping your script with document.ready; I suspect that you're script might be running before your entire page loads.

JQuery: How can I extend a script over some dynamically loaded content?

I have a little problem that I was hoping some of you could help me out with.
On clicking a button, I would like to update a div with the content of another page.
Let's say that homepage.html is like this:
<html>
<head>
<script type="text/javascript" src="JQUERY.JS"></script>
<script type="text/javascript">
$(function()
{
$(".alert").click(function()
{
alert("HELLO");
return false;
});
$(".load").click(function()
{
$("#content").load("FILE.HTML");
return false;
});
});
</script>
</head>
<body>
CLICK ME
<div id="content"></div>
</body>
</html>
A rather simple file.
Now let's say that FILE.HTML has this line only:
CLICK ME
Now what I am looking for is: when i click .alert, the alert box pops up. I don't know why it doesn't.
So my question is: why is my loaded code not affected by the script?
Thank you for your help.
You need to use the jQuery Delegate to achieve that...
The contents from file.html are not present the moment you attach the click event to the ".alert" items (actually there are no .alert items when that code runs!).
You need to use jQuery's delegate or live methods which use event bubbling in order to capture events not only from existing elements but also from new elements that are inserted in the DOM later.
This also has the nice side effect of using only one event handler instead of one for each .alert element.
You have to use $.live:
$(".alert").live('click', function()
{
alert("HELLO");
return false;
});
You don't have to wait until you add in your dynamic content, this function applies your event handler to all future elements that match your selector.

Categories