In my script I have 2 functions. First function references to a div element, creates a paragraph element inside div and appends some text to this paragraph element;
In my second function is triggered by onclick event attached to a link element. I want the text in the div to be changed to another text when clicking on the link. I do realize that there are 2 options how to achieve this:
1) declare global variables and use them in my second function;
2) pass the variable value from first function to the second function and manipulkate this value from the second function
But the question is how to do I correctly pass the variable value from first function to second function:
Here is the code:
<a href=''onclick='change();return false;'>Change</a>
<div id='box'></div>
Javascript:
window.onload= function createEl(){
var el = document.createElement('p');
var x = document.getElementById('box');
var text = 'text';
el.appendChild(document.createTextNode(text));
x.appendChild(el);
}
function change(){
x.innerHTML="other text";
}
in general you can write this:
function one(){
var var1 = "hello";
two(var1);
}
function two(x){
alert(x);
}
this will alert "hello".
For what you're doing, I would register my events through code to make it easier to pass a variable. We want to use an argument in the event handling function to pass the data to it.
window.onload = function()
{
// do your normal stuff with creating elements
var anc = document.getElementById('ID of your a element here');
if(anc.attachEvent)
{
//code for ancient IE
anc.attachEvent('onclick', function(){change(x);});
}
else if(anc.addEventListener)
{
//code for modern browsers
anc.addEventListener('click', function(){change(x);});
}
}
function change(elem)
{
elem.innerHTML='other text';
}
Do note that older versions of IE don't recognize addEventListener and use attachEvent instead, as seen in the above if block. Here's the documentation for addEventListener.
Related
I want to add on-click function to my dynamic div tag in JavaScript.
divElement = document.createElement('div');
divElement.onclick = moveImages(j, k);
I want to pass two parameter to the moveImages() function.
In pure Javascript you need to define the onclick as a function, just like this:
divElement.onclick = function(e) {
moveImages(j,k);
};
Without it, Javascript will simply call the function and assign the return value to the "property" onclick.
That (e) parameter is just in case you need to know where the click was and things like that.
You can achieve that by doing the following:
var divElement = document.createElement("div");
function moveImages(j, k){
/* ... */
}
divElement.addEventListener("click", function() {
moveImages(j, k);
}, false);```
The JSFiddle below is a simplified example of what I am trying to accomplish.
My code generates a. anchor element that is passed to a div.
I'd like it to return its id when double clicked but get an undefined instead.
Can anyone tell me what I am doing wrong?
JSFiddle
function abc() {
var myString = "<a onclick='bcd(this);' id='1'>krokodil</a>";
document.getElementById("output").innerHTML = myString;
}
function bcd(e) {
alert(this.id);
}
The value of this depends on how you call the function.
Since you are calling bcd without an explicitly object (foo.bcd()) and are not in strict mode, the value will be equal to window (in a browser).
You are reading the id of the window, not the element.
Look at the e variable instead of this (since you pass it the element from the click event handler).
The parameter you are passing to the alert function is referenced as e, but you then attempt to alert this.id. this refers to the function calling the expression. Try this:
function abc() {
var myString = "<a onclick='bcd(this.id);' id='1'>krokodil</a>";
document.getElementById("output").innerHTML = myString;
}
function bcd(e) {
alert(e);
}
Note that you also need to update the onclick() event to include the id property
The problem is you are alerting the id of this, which is not equal to e in the scope of the function. Change the function to
function abc() {
var myString = "<a onclick='bcd(this);' id='1'>krokodil</a>";
document.getElementById("output").innerHTML = myString;
}
function bcd(e) {
alert(e.id);
}
<button type="button" id="button" onclick="abc()">ADD</button>
<div id="output">kikker</div>
change
alert(this.id); to
alert(e)
I want to start off by saying I'm not an expert, maybe not even an intermediate, user of jQuery and any and all help is appreciated.
Here is a simulation of my little problem:
https://jsfiddle.net/c897enhy/
<a id="someRandomID_hypNotifSentTo_0" class="NotifSent2" href = "#">
this is the text i want to get
</a>
<br>
<a id="someRandomID_hypNotifSentTo_0" class="NotifSent2" href = "#">
this is the text i want to get 2
</a>
<br>
<a id="someRandomID_hypNotifSentTo_0" class="NotifSent2" href = "#">
this is the text i want to get 3
</a>
if ($) {
$(document).ready(function () {
$("a[id*='_hypNotifSentTo_']").live("click", function ($e) {
// Will post list of recipients to be removed from the file
var x = $(this).text();
alert(x);
AjaxSuccessPopulateRecipients("restult");
});
function AjaxSuccessPopulateRecipients(result) {
alert("asdf");
var x = $('#NotifSent2').toString();
alert(x);
var x = $(this).text();
alert(x);
var recipients = $(this).text();
alert("1");
var recipientArr = recipients.split(',');
}
});
}
While, I am able to get the text of the active link from the "click" event, I am unable to do so from my second function.
The way the application works, is that the first function call ajax c# file, which then returns a success into the second jquery function with some results from c#.
I need to compare the results that are returned from the c# to what is inside the clicked hyperlink, but am unable to get the clicked text from within that "AjaxSuccess" function.
You're losing the the context of $(this) when you're in the Ajax function ($(this) will no longer refer to the clicked link). Try adding a variable that you can store the context in, like so:
$(document).ready(function () {
var $that;
$("a[id*='_hypNotifSentTo_']").live("click", function ($e) {
// Will post list of recipients to be removed from the file
$that = $(this);
var x = $that.text();
alert(x);
AjaxSuccessPopulateRecipients("restult");
});
function AjaxSuccessPopulateRecipients(result) {
alert("asdf");
//var x = $('#NotifSent2').toString();
//alert(x);
var x = $that.text();
alert(x);
var recipients = $(this).text();
alert("1");
var recipientArr = recipients.split(',');
}
});
$(this) inside the AjaxSuccessPopulateRecipients refers to the Widow object and not the anchor tag that was clicked.
Just send the reference of anchor tag from click event to the second function like this
AjaxSuccessPopulateRecipients("restult", $(this));
Use it as context like this
function AjaxSuccessPopulateRecipients(result, context) { // <--- context refers to the anchor tag
alert("asdf");
var x = $('.NotifSent2').text();
alert(x);
var x = context.text();
alert(x);
var recipients = context.text();
alert("1");
var recipientArr = recipients.split(',');
}
Take a look at Function.prototype.call().
The call() method calls a function with a given this value and
arguments provided individually.
Change:
AjaxSuccessPopulateRecipients("restult");
To:
AjaxSuccessPopulateRecipients.call(this, "restult");
Doing so will pass the correct this value to your function.
You should not able to access data via this $('#NotifSent2') selector as the # selector is JQuery syntax for finding an ID on the page, whereas your elements are constructed with class="NotifSent2".
If you wish to access a variable from a different function, you must ensure that the variable is within the correct scope.
Since your AJAX call and AjaxSuccessPopulateRecipients() function are within the same scope, you do not have access to $(this) across the two.
Simply pass the variable you wish to use to your function, as $(this) AjaxSuccessPopulateRecipients("restult", $(this));
I want to create a function and then use with onclick method, for example:
one = document.getElementById("oneID");
then instead of writing function for each onclick():
one.onclick = function(x) {
tempStack.push(parseFloat(one.value));
viewTemp.value += one.value;
}
I want to use a single function:
one.click = input(one);
but I'm not sure how to do it in the correct way for example the below I tried, doesn't work:
var input = function(x) {
tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;
}
Lastly, no external JavaScript libraries to aid this question, vanilla JavaScript.
You'll need to pass a function as a reference, not call it:
one.onclick = input;
In this case you won't be able to pass an argument, but you can use this as a reference for the DOM element on which event is fired:
function input() {
tempStack.push(parseFloat(this.value));
viewTemp.value += this.value;
}
Here's a method with using JavaScript's .addEventListener(), as a previous answer mentioned, using this to pass through the DOM Node Element to use within the inputFunction.
<input type="text" value="64.23" id="bt" />
<script>
function inputFunction( x ) {
console.log( x.value ); //Console Logs 64.23
}
var bt = document.getElementById("bt");
bt.addEventListener( 'click', function(){ inputFunction( this )}, false );
</script>
Fiddle: http://jsfiddle.net/Lhq6t/
Think about functions as a normal objects, so the way is:
function input (event) {
// Process the event...
// event is my event object
// this is the object which trigger the event
// event.target is my button
}
on.onclick = input;
You must assign the input function as a normal variable.
The function input will receive an event object as parameter. Also you can refer to the button clicked with this.
Maybe the mozilla developer network or the real w3c site would explain it better.
Your requirement can be achieved by following:
Add this method in your script tag:
function input(x) {
/*tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;*/
alert(x.id);
}
And then call this method onClick event of your buttons / anchors like:
<input type="button" id="oneID" value="oneID" onClick="input(this);"/>
<input type="button" id="twoID" value="twoID" onClick="input(this);"/>
threeID
See working example: http://jsfiddle.net/Avd5U/1/
ok, so just create a function with a parameter in it like:
function setValue(input){
tempStack.push(parseFloat(input.value));
viewTemp.value += input.value;
}
and then call the function on the click of that element like:
var one = document.getElementById("oneID");
one.click = setValue(one);
Good luck!
I am creating an array & assigning the value to each index in a function through variables.
I also want to attach a jquery click method to each variable. However, I am getting 'undefined' in return when the click method is called.
var i = 0;
var eCreditTransactions = new Array(6); // 6 members created which will be recycled
function abc()
{
addingElements (i);
}
/* **** THE FOLLOWING IS THE PROBLEM AREA **** */
$(eCreditTransactions[i]).click (function () // if user clicks on the transaction box
{
creditTransactionSlideIn (eCreditTransactions[0], 150); //another function called
});
/* **** this is the function being called in the first function above **** */
function addingElements (arrayIndex) // func called from within the 'createCreditTransaction()' func
{
eCreditTransactions[i] = $(document.createElement('div')).addClass("cCreditTransaction").appendTo(eCreditSystem);
$(eCreditTransactions[i]).attr ('id', ('trans' + i));
$(eCreditTransactions[i]).html ('<div class="cCreditContainer"><span class="cCreditsNo">-50</span> <img class="cCurrency" src="" alt="" /></div><span class="cCloseMsg">Click box to close.</span><div class="dots"></div><div class="dots"></div><div class="dots"></div>');
creditTransactionSlideOut (eCreditTransactions[i], 666); // calling slideOut animation
counterFunc ();
return i++;
}
Try this:
$(document).ready(function() {
$(".cCreditTransaction").click(function() {
//do what you want on click event
});
});
Hope it helps
Given that it looks like each element you're adding to the array has a classname (cCreditTransaction) you can hookup the click events using something like
$(document).delegate(".cCreditTransaction", "click", function() {
// code to fire on click goes here.
});
or in jQuery 1.7+ you can use .on instead of .delegate
You don't then need to hook up n events, but just one event that matches all items in the selector (in your case, the class name)
You should also change $(document) to a container element that has an Id, so that the DOM traversal to find the classes is trimmed down as much as possible. Why? Because finding elements by class name is a relatively expensive procedure, as opposed to finding tags or even better, an ID.
it looks like there should be a loop in this part:
function abc()
{
addingElements (i);
}
there is a call to addingElements, and an 'i' parameter being passed, but 'i' is at that moment still defined as 0.
it should say something like
function abc()
{
for (i=0;i<=7;i++)
{
addingElements (i);
}
}