How to get selector's variable on Onclick - javascript

When a selector is assigned to a variable, I need to get that variable name on onclick I have created a Fiddle as an example
var $main_img1 = $("<div/>").addClass('add1').appendTo($('#main_container'));
var $main_img2 = $("<div/>").addClass('add2').appendTo($('#main_container'));
$main_img1.click(function()
{
get_id()
});
$main_img2.click(function()
{
get_id()
});
function get_id(event)
{
console.log($(this))
alert('i need to get selector variable on click')
}
Output should be $main_img1 and $main_img2 when I click on the corresponding div

Here is a solution, but not sure how you are going to use it
Used Array to get the variable name.
JS
var arr = new Array();
arr[0] = '$main_img1';
arr[1] = '$main_img2';
var $main_img1 = $("<div/>").addClass('add1 add').appendTo($('#main_container'));
var $main_img2 = $("<div/>").addClass('add2 add').appendTo($('#main_container'));
$main_img1.click(function()
{
get_id($(this))
});
$main_img2.click(function()
{
get_id($(this))
});
function get_id(event)
{
alert(arr[$('.add').index(event)]);
}
Update : No array needed.
function get_id(event)
{
///var temp = '$main_img' + (parseInt($('.add').index(event)) + 1);
var temp = '$main_img' + (parseInt($('#main_container > div').index(event)) + 1);
alert(temp);
console.log(eval(temp));
}
Updated DEMO

I suggest a workaround.. see if it helps you. Add a hidden element inside the corresponding divs and add the variable names as text to it. I slightly modified your method get_id() to get the variable name from your divs hidden element.
function get_id()
{
console.log($(this))
var selVar= $(this).parent().find('input:hidden:first').text();
alert('selector variable' + selVar);
}
this will work for you.

You could maybe guessing from the class of the element you click on it and use reflexivity.
To know the element you click on it, just use event.target where event is a variable passed in the click function. Look at this fiddle for an example.
The get_id method now looks like this:
function get_id(event) {
console.log(event.target)
}
The value returned by event.target is the same as the value returned by the variable you declare it ($main_img1 or $main_img2).

Related

How do you get html attributes in a javascript function with a variable element?

When a user clicks on an element in my HTML, I want a new tab to appear in their browser and the attributes of the element they clicked on to be printed in that window.
This is a typical element in the HTML:
<a id="d0e110" onclick="GetWordFile(this.id)" attr1="attr1_value" attr2="attr2_value" attr3="attr3_value">ElementContent</a>
There are many such elements. The UID is generated for each one during the XLST transformation ('id="{generate-id()}"').
This is my current javascript function:
<script>
function GetWordFile(id) {
var opened = window.open("");
opened.document.write();
}
</script>
If the last line of the function is "opened.document.write(id);", and an element is clicked, then the new window displays the correct UID for the clicked element. So the connection has been successfully established.
However, I cannot make any other attributes of the element appear in the new window. The following function, for example, produces a blank new window:
<script>
function GetWordFile(id) {
var opened = window.open("");
opened.document.write(attr1);
}
</script>
So does trying to get the attribute as a variable:
<script>
function GetWordFile(id) {
var opened = window.open("");
var a1 = getAttribute("attr1");
opened.document.write(a1);
}
</script>
I've also tried substituting inner HTML for document.write.
Can anyone identify what I am doing wrong and what my next steps should be?
You can pass this.attributes to the function, .filter() attributes that are not onclick, .map() the .value of the attributes to an array
<script>
function GetWordFile(attrs) {
attrs = [...attrs].filter(attr => {
return attr.name !== "onclick"
}).map(attr => attr.value);
console.log(attrs);
}
</script>
<a id="d0e110" onclick="GetWordFile(this.attributes)" attr1="attr1_value" attr2="attr2_value" attr3="attr3_value">ElementContent</a>
You need to call getAttribute() as a method of the element, which you can get using document.getElementById().
function GetWordFile(id) {
var el = document.getElementById(id);
var attr1 = el.getAttribute('attr1');
var opened = window.open("");
opened.document.write(attr1);
}
Instead of passing this.id as the function argument, you might consider just passing this. Why force the function to search for the element when you can just provide it directly? Then the function would be like:
function GetWordFile(el) {
var attr1 = el.getAttribute('attr1');
var opened = window.open("");
opened.document.write(attr1);
}
When you are loading a new window you are creating a new document that does not necessarily know that any other documents exist. In order for the document to know that any other documents exist you must pass in the desired information as a parameter so as mentioned above.
onclick="someFunction(this)" // which passes in the current scope
// you could then define someFunction like so to get the desired
// result
function someFunction ( htmlObject ) {
attributeList = htmlObject.attributes;
attributeArray = [...attributeList];//now can perform arrayfunctions
let a = "";
for (value in attributeArray) {
a += attributeArray[value].value + " "; // creates a string of
attributes
}
let s = window.open("");
s.document.write(a)}
Note you probably want to do some array filtering because it will return all attributes but the general principle works.

Getting "This" into a namespace in Javascript

I'm sure this should be a simple question but I'm still learning so here it goes:
I have some code to run a function on click to assign the clicked element's ID to a variable but I don't know how to pass the "this.id" value to the namespace without making a global variable (which I thought was bad).
<script>
fsa = (function() {
function GetTemplateLoc() {
templateId = document.activeElement.id;
alert(templateId + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc();
});
</script>
and HTML with random picture:
<img id="template-1" class="template" src="http://fc02.deviantart.net/fs70/f/2010/028/c/b/cb21eda885b4cc6ee3f549a417770596.png"/>
<img id="template-2" class="template" src="http://fc02.deviantart.net/fs70/f/2010/028/c/b/cb21eda885b4cc6ee3f549a417770596.png"/>
The following would work:
var fsa = (function() {
function GetTemplateLoc() {
var templateId = this.id;
alert(templateId);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', fsa.GetTemplateLoc);
jQuery generally calls functions you pass as event handlers with this set to the DOM object the event is associated with.
In this case it will call GetTemplateLoc() with this set to either .template element, so you can use this directly in the function and don't need to pass any parameters.
Important tip: Always declare variables using var. JavaScript has no automatic function-local scope for variables, i.e. every variable declared without var is global, no matter where you declare it. In other words, forgetting var counts as a bug.
Try this : You can directly use this.id to pass id of the clicked element where this refers to the instance of clicked element.
<script>
fsa = (function() {
function GetTemplateLoc(templateId ) {
//templateId = document.activeElement.id;
alert(templateId + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc(this.id);
});
</script>
If you're able to use jQuery within the GetTemplateLoc function, you could do something like this:
var fsa = (function() {
function GetTemplateLoc($trigger) {
var templateId = $trigger.attr('id'),
templateId2 = $($trigger.siblings('.template')[0]).attr('id');
alert(templateId + ' ' + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc($(this));
});
You can set GetTemplateLoc to expect a jQuery object as a parameter (the dollar sign at the beginning of $trigger can be used to distinguish it as a jQuery object rather than any other data type, it's not necessary but can help clarify things sometimes).
templateId will store the value of the clicked image's ID, and templateId2 will store the value of the other image's ID. I also added a space between the two variables in the alert.
If you can't use jQuery within GetTemplateLoc, you could do something like this:
var fsa = (function() {
function GetTemplateLoc(trigger) {
var templateId = trigger.id;
var templateId2 = trigger.nextElementSibling == null ? trigger.previousElementSibling.id : trigger.nextElementSibling.id;
alert(templateId + ' ' + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
This time, the .template that triggered the event is passed into GetTemplateLoc, but this time it's not a jQuery object. templateId is assigned to the trigger's ID and then templateId2 is assigned in a ternary. First, the nextElementSibling of trigger is checked to see if it's null. If it is, we know that trigger is the second of the two .template elements. Therefore we can set templateId2 to the ID of trigger's previous sibling. If trigger's nextElementSibling is not null, then we know that trigger is the first template and we populate templateId2 with the ID of nextElementSibling. This exact method will only work with two .template's, if there are more you'll need some additional/different logic, probably to retrieve all .template IDs and then loop through them to add them to the alert message. Hope this helps.

'alert' an object property on click

I have a constructor which I then make the object library_science1 with:
function librarytech(humanity,food,wood,metal,wealth)
{
this.humanity=humanity;
this.food=food;
this.wood=wood;
this.metal=metal;
this.wealth=wealth;
}
var library_science1=new librarytech(0,200,200,0,0);
I have this as a click function:
$("[id^='library_']").click(function() {
var idd = this.id;
alert(idd);
});
where the html is simply
<span id='library_science1'></span>
The code above works fine, alerting 'library_science1' nicely... it even works when I use the alert to directly pull one of the objects properties.
$("[id^='library_']").click(function() {
alert(library_science1.food);
});
But I have many library_[SOMETHING] objects, corresponding each to there own
<span id="library_[SOMETHING]"></span> line.
I'm trying to pull the objects properties depending on which one is clicked. Such as:
$("[id^='library_']").click(function() {
alert(this.id.food);
});
or
$("[id^='library_']").click(function() {
var x = this.id;
alert(x.food);
});
The end purpose being that I can ultimately do things like:
foodamount -= this.id.food
Why isn't this working :/ :(
simply because you are accessing an object in your first example and not a DOM object as in other, if their obejtos are global so you can access
alert(window[this.id].food);
or
alert(eval(this.id + ".food"));
I made a test here using eval() and this works:
$("[id^='library_']").click(function() {
alert(eval(this.id).food);
});
$("[id^='library_']").click(function() {
var x = eval(this.id);
alert(x.food);
});

return a variable from .click() javascript function

First of all excuse for my weak english, I try to use the following javascript code and I want to return id variable and use it in other function, but it seem does not work correctly and does not return it, can someone help me out writting this
var idcb = $('.box').click(function() {
var id = $(this).attr('id');
return id;
});
I want to use var idcb in this function :
$(".hs").click(function() {
$(idhs).slideToggle("slow");
return false;
});
});
for that to work, the jquery click implementation would need to know that the function you pass it returns a value, and that it itself should return that value - which isn't the case.
instead, you could use some closure magic to do this easily. try this:
var idcb;
$('.box').click(function() {
idcb = $(this).attr('id');
});
You are passing an anonymous function to an event handler, you cannot return a value from this type of function. The solution is to use closures to get around this :
var idcb = null;
$('.box').click(function() {
idcb = $(this).attr('id');
});
The variable idcb will always be set to the id of the last .box that was clicked.
The function is given as a parameter to the click function and is run asynchronously when the user clicks on an element. So you can't return a value directly, since the function won't be run immediately. You can look up the id value another way, or pass it to a function to work with instead of returning it, or just do this:
var idcb = $('.box').click(function() {
var id = $(this).attr('id');
$(id).slideToggle("slow");
});
You cannot do it the way you are trying to. However, what you can do is use a variable that is accessible by both functions to share values between them.
var icdb = 'test';
function a() {
icdb = 'another value';
}
function b() {
console.log(icdb);
}
a();
b();
You could also call b from a and pass the variable as argument:
function a() {
b('test');
}
function b(icdb) {
console.log(icdb);
}
a();
your variable idcb contains the click handler !
you need to declare the vriable outside the handler and assign to it inside to make this work:
var idcb = null;
// ... whatever
$('.box').click(function() {
idcb = $(this).attr('id');
return true; // return 'true' from an event handler to indicate successful completion
});
Check this out
var id=null;
$('.box').click(function() {
id = $(this).attr("id");
});
$(".hs").click(function() {
$("#"+id).slideToggle("slow");
return false;
});
You could pass in the an object as a reference to the click function
and change the value from the callback. Another option is using closures
The caveat to this jsfiddle is that you have to call a .box element first.
http://jsfiddle.net/D6B73/2/
var idcb = {};
$('.box').click(idcb, function (event) {
event.data.value = $(this).attr('id');
console.log(idcb.value);
});
$('.hs').click(function() {
$('#'+idbc.value).slideToggle("slow");
});
You can do it this way:
$(".hs").on('click', function() {
var id = $('.box').attr('id');
alert(id);
});

.innerHTML function Javascript

This is my code:
function text(var text)
{
var Value = document.getElementById("display").innerHTML;
var New = Value + text;
document.getElementById("display").innerHTML=New;
}
What it's supposed to do is get a string from when it's called, and then add that string to the end of a div element with the ID "display". I called it like this: text("hello");
The HTML of the webpage is a blank div element, and it stays blank even after the code is run. It worked when I did document.getElementById("display").innerHTML="hello!";, but isn't now. Thanks!
Don't use "var" for a function parameter - just listing it between the function parenthesis is enough. So change that function to:
function text(text)
{
var Value = document.getElementById("display").innerHTML;
var New = Value + text;
document.getElementById("display").innerHTML=New;
}
and it should work.
Take the var out of the function parameter: function text(text)...
BTW: don't name your parameter the same thing as your function - it's confusing.
And you can do it like this:
function text(inputText)
{
document.getElementById("display").innerHTML = document.getElementById("display").innerHTML +" "+ inputText;
}
:)

Categories

Resources