How can I call a function at a click of a button? - javascript

I recently started playing around with javascript for fun.
I worked myself through the most of w3schools tutorial (including jquery ofc).
The point where i got stuck is simply calling a function at a click of a button.
My code (edited to provide a Minimal, Complete, and Verifiable example)
$("#linkId1").on("click", function(){
setTimeout(function(){
function decryptText() {
alert( "decrypted!" );
}
$("tableId").append('<a id="decryptID" class="button">decrypt</a>');
$("#decryptID").on("click", decryptText);
}, 500);
});
HTML:
<a id="linkId1">firstLink</a>
<table>
<tbody>
<tr>
<td id="tableId">
<a id="button1" class="button"></a>
<a id="button2" class="button"></a>
</td>
</tr>
</tbody>
</table>
Here's what i've already tried:
Different approaches to calling the function
Making the function decryptText() global or local
- Adding an eventListener to the button after creating it (because I read on another post that it's better to use the eventListener
than putting the onclick attribute in the HTML-tag). ~I mixed
basic js with jQuery methods here - BIG mistake.
The browser console does not give me any errors - when I changed to code a bit, I got: Reference Error: decryptText() not defined
S.
EDIT:
I tried doing it all in jQuery only, the selectors and the event handling.
As you can see, I changed the example code to the beginning of a simple encrypt and decrypt script - the core problem still stays the same though.
Checking with Firefox' inspector tool, this time the element does not have any event bound to it.
A probably important piece of information is that the table you can see in the HTML does not exist before an onclick ajax handler is called from the element #linkId1 and inserts the whole div containing the tables into the html.

I solved it!
(Thanks to Cbroe & Se0ng11)
Code before:
$("#tableId").append('<a id="decryptID" class="button">decrypt</a>');
$("#decryptID").on("click", decryptText);
Code after:
$("#tableId").append('<a class="button">decrypt</a>');
$(".button:contains('decrypt')").on("click", decryptText);
The problem was created by the static ID i assigned to the hyperlink element I append() in line 1.
Removing the ID and changing the jQuery selector in line 2 worked!

I'm going to provide an alternative solution to your problem. If you create the element as a fully fledged jQuery before you append it to the table you can bind the click event directly to this without having to find it again:
var newA = $('<a\>').addClass('button').text('decrypt');
newA.on("click", decryptText);
$("#tableId").append(newA);
$('<a\>') will create the DOM element as a variable before you append it to the DOM. The main advantage here over your current code is this will guarantee that that click is bound to that <a> tag, even if you have multiple elements with the same text(decrypt). I'm mainly saying this becuase the selector you use ".button:contains('decrypt')" is pretty vague and could match things that your not expecting or event bind a handler twice if you run the same code twice.
Another option is to bubble the events using delegation:
$("#tableId").on('click', '.button', decryptText);
the event handler is now bound to the static item tableId but it's listening for events that match the underlying class button. This is covered comprehensibly here Event binding on dynamically created elements?
With the above you can happily add as many new <a> as you want safe in the knowledge that the event binding is already dealt with, i.e. you don't have to bind the event on creation.

Try this, you was missing few things, $(document).ready(function () {} and $("tableId").append(...); should be using # $("#tableId").append(...); because tableId is id of the element not element itself. It will work with W3c as well it is not like you should not use this or that because of you are beginner. you can use any where.
$(document).ready(function () {
$("#linkId1").on("click", function () {
setTimeout(function () {
function decryptText() {alert("decrypted!");
}
$("#tableId").append('<a id="decryptID" class="button">decrypt</a>');
$("#decryptID").on("click", decryptText);}, 500);});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table><tr><td>
<a id="linkId1">firstLink</a></td>
</tr>
<tr><td id="tableId">
<a id="button1" class="button"></a>
<a id="button2" class="button"></a>
</td>
</tr>
</table>

Related

jquery sometimes does not work

so I have been having this problem I have a div with 2 buttons in my HTML
<div id="carosel">
<button class="navigation" id="nav-left"><</button>
<button class="navigation" id="nav-right">></button>
</div>
and in my jQuery code, I have this function
$("nav-left").hover(function() {
alert('something');
});
when I try from console sometimes it works. I have referenced the javascript file in the header correctly.
The problem is quite simple, you forgot a "#" initiative at the beginnging the selector, you should try run the following
$("#nav-left").hover(function() {
alert('something');
});
Two problems:
First, your selector should be #nav-left. jQuery uses css selectors, so you need to use the # to reference an element with an ID of nav-left. (Whereas you would use .nav-left if your element had a class of nav-left rather than an id)
Second, when you move from the console to your own file (or inline script), you will want to wrap your JavaScript in a
$(document).on('ready', function (){
<Your code here>
})
This will ensure that your DOM will have actually renderered before you try to manipulate it with jQuery.

Why do I need 'javascript:' in the call to my javascript function?

Newer to javascript and trying to learn why this works, searching Google has led to no answers (although I maybe searching using the incorrect terms).
I'm am making a call to a function during an onclick event within an <a></a>. I was able to get the function finally working (with a suggestion from a coworker) by adding in 'javascript:' before making the function. Without the javascript: portion in the onclick, my function was not being called upon.
It now works but I don't understand what that is doing, the other programmer who suggested putting it in the call also isn't sure what exactly it does.
Here is a simplified version of the code used:
#1 .jspf higher up which includes page #2 to display it's contents
function createTagging(1, 2) {
cmCreateElementTag(1 + ", " + 2,"TagName");
}
HTML in .jspf file #2 further down website makes the call to function in file #1
<a id="CatEntry" href="https://aurl"
onclick="javascript: createTagging('parameter1', 'parameter2');"
title="atitle" aria-label="alabel">
<img id="ThumbNailImage_59244" src="https://image.jpg"
alt="" border="0"/>
</a>
-Troy
Why do I need 'javascript:' in the call to my javascript function?
You don't. It's an onclick handler. You use the javascript: pseudo-protocol where a URL is expected (for instance, if you'd used href instead of onclick). onclick expects JavaScript code.
In fact, it only works because JavaScript has labelled statements, and javascript: is a valid label. It's completely ignored.
Without the javascript: portion in the onclick, my function was not being called upon.
With respect, that must have been observational error. Again, in an onclick handler, it makes no difference whether you have javascript: in front of it or not. If it wasn't working, and then it was working, you changed something else at the same time you added javascript:.
onclick attribute is always calling javascript in HTML.
onclick="createTagging('parameter1', 'parameter2');"
It is only necessary if you use not an event, but href. There you need to add the protocoll as well for Javascript.

Why wont my appendChild work?

I have a little javascript app set up here: http://jsfiddle.net/faYMH/
What i want it to do is add a
<div><h1>Hi there and greetings!</h1></div>
after
<div id='org_div1' onclick="addElement()">Hello</div>
using
<a href="#" onClick="addElement()" >add some</a>
(actually, what i want is for the onClick to go directly in the
So can anyone correct my code or provide some input?
(My next step is to also add a remove div, add an id to the new div with id + i++ )
Thanks so much!!
That's a quirk of JSFiddle. It wraps all of your code in a closure, so onclick handlers can't access your function. Either export the function into the global scope:
window.addElement=addElement;
Or change the little drop down in JSFiddle from "onLoad" to "no wrap (head)" or "no wrap (body)". While you're at it, you might want to change "Mootools" to "No-Library (pure JS)".
In your jsFiddle, addElement was scoped to inside the document ready handler and thus wasn't available to the click handler. I've modified the settings in the jsFiddle (without changing any code) to not have your code wrapped that way and it works for me now: http://jsfiddle.net/jfriend00/XVDYa/.
I changed the jsFiddle settings to "No-Library (pure JS)" and to "no wrap (head)". It's the second setting that really makes the difference here.

javascript that produces functioning javascript

can you write javascript that produces/writes/etc. functioning javascript?
for example, have a link that has a function tied to it that when clicked produces a functioning javascipt snippet? The snippet could deal with a completely other elements.
For example
Link #1(has the javascript function that produces javascript) Link #2(does absolutely nothing for now)
Click on link #1(produces javascript snipped that says "when link #2 is clicked document.write('hello')"
Clicking on link #2 now produces "hello" whereas it previously did nothing. Is that possible?
Yes, you can dynamically assign event handlers described in text.
However, dynamic code generation is far more difficult than it sounds unless you're just following basic patters and replacing certain variables. Writing programs that write programs has long been a fascination of the computer industry, and this gave way to functional programming, which can be done in javascript.
Create the input/delete keys on the onClick handler for the datepicker, you can attach date information (or other data) when the input(s) are created. Now, you should look into $.delegate() for how to bind handlers to those inputs created. $.delegate can bind handlers to elements that are not created yet, so when they are created they will fire a handler. By storing date relevant information in the inputs via $.data() or data- attributes you will have context aware handlers for dealing with things.
If I understand your question correctly, you could do what you want with the code below.
Not sure why you'd want to do this, though.
can you write javascript that produces/writes/etc. functioning javascript?
You can do this the way I did it, or by using eval -- though, as many coders have pointed out, eval is evil!
<html>
<head>
<script type="text/javascript">
function initLinks(){
document.getElementById("link1").addEventListener("click", function(){
document.getElementById("link2").addEventListener("click", function(){
document.write("hello");
}, false);
}, false);
}
</script>
</head>
<body onload="initLinks()">
<a id="link1">Link 1</a>
<a id="link2">Link 2</a>
</body>
</html>

what are the "for" and "event" attributes of the script tag (Javascript,HTML)

In a web application I've inherited at work which was written about 10 years ago I've noticed the following code snippets repeatedly used:
<script language="JavaScript" for="FG1" event="Mousedown(Button, Shift, x, y)">
{
// some code here that uses the variables Button, Shift, x and y
}
</script>
I've never really seen anything like this before. FG1 is an active x object so are these some special things for it specifically or are they just another way of handling any regular javascript event...could the ID reference an input (e.g. a button) and the event be onclick?
ideally, i'd re write it as (if my thinking is correct...I'm not actually going to change the code in the web app as it works, i just want to understand what it means!)
<script type="text/javascript">
var fg1 = document.getElementById("FG1");
fg1.onMouseDown = function(Button, Shift, x, y) {
// do stuff here...
}
</script>
Those are Microsoft-specific (Internet Explorer-only) extensions to the script tag, and your impulse to rewrite the example without them is a good one.
According to MSDN, the:
for attribute:
Sets or retrieves the object that is bound to the event script.
event attribute:
Sets or retrieves the event for which the script is written.
Therefore, I presume as you have that you can drop the non-standard attributes and use the lines you added to get the element, and handle the mousedown event.
for attribute is for the element name in for attribute like for="element1" and event attribute is for event handling like even onclick, onmouseover etc for that elements.
For example if you add Onclick event then onclick event works on element which name you entered in for attribute.
I have seen this kind of code snippet in a classic ASP project, where it uses a simple vbscript form validation method. `
<input name="button1" type="button" id="button1" value="Submit">
<script language="VBScript" for="button1" event="onClick">
Menu_Validate()
</script>
This onclick event will call the Menu_Validate() method and do form validation.

Categories

Resources