jquery body on hover cannot target other DIVS - javascript

I am trying to access my own javascript function from within a:
$("body").on("mouseenter",".noteNode",function(){});
The trouble seems to be that when I am inside the function above jQuery will not allow me to get access to other elements?
Let me elaborate further:
Actual code I want to use I've jsfiddled: http://jsfiddle.net/uJ2Yb/8/
I believe the function is being called as I had wanted it to be, but as you can see $(this) is not able to target the actual div which is being hovered, and so when trying to pass this data to the other function it just doesn't arrive - why is this? I believe it's a scope problem but I have tried a few ways to solve it and searched S.O without much luck yet.
The reason I need to use $("body").on is because I am creating the DIV's (which will be hovered) on the fly with JS.
As you can see the hover function is working fine and firing as it should do, but totally unable to access anything in the DOM which I don't understand
.
[Edit] so to clarify: http://jsfiddle.net/uJ2Yb/8/
I am trying to pass the ID of the DIV (which was created BY JS) over to my own function in which i want to try and access the DIVs offset parameter - but i am unable to do so, you will see in my revised fiddle that i am just getting 'undefined' in my alert box which is not what i wanted - i am still convinced that this is because of a scope issue.

try this updated fiddle: http://jsfiddle.net/uJ2Yb/7/
function myFunction(someVar){ alert(someVar); }
$("body").on("mouseenter",".noteNode",function(event){
myFunction(event.target.innerHTML );
//alert( event.target.innerHTML );
});

Please Assign Unique Id To Your Divs
try This Code
function myFunction(someVar){ alert(someVar); }
$(document).ready(function(){
$("body").append('<div class="noteNode" id="a">Note Node</div>');
$("body").append('<div class="noteNode" id="b">Note Node</div>');
$("body").append('<div class="noteNode" id="c">Note Node</div>');
});
$("body").on("mouseenter",".noteNode",function(){
myFunction( $(this).attr("id") );
alert( $(this).attr("id") );
});

Related

Passing parameter to javascript onclick without using HTML

I can't figure this out. I'm trying to create an onclick handler purely in Javascript.
What I plan to do here is inside this DIV, have a collection of items that I can click on. For now, these items will be numbers from 0 to 9 inclusive. When a number is clicked on, a system message consisting solely of that number should pop-up on the screen. I narrowed my problem down to just the onclick handler definition.
If I use this format:
item[n].onclick=function(n){
handler(n);
}
The handler will fire only when click a number which is correct, but the message that appears is something about mouse event.
If I use this format:
item[n].onclick=function(){
handler(n);
}
The handler will pass a value of -1 which in turn is printed as a message. I think it means "false".
How do I modify this:
item[n].onclick=function(){
handler(n);
}
so that 'n' being used as the handler parameter is the same as the number I click on the screen?
My code is the following:
<div ID="Itemset"></div>
function handler(n){
alert(n);
}
collections=document.getElementById('Itemset');
for(n=0;n<10;n++){
item[n]=document.createElement('DIV');
item[n].innerHTML=n;
collections.appendChild(item[n]);
item[n].onclick=function(n){
handler(n);
}
}
What I'm effectively trying to do if you want to understand it HTML wise is this:
<div ID="Itemset">
<div onclick="handler(0);">0</div>
<div onclick="handler(1);">1</div>
<div onclick="handler(2);">2</div>
<div onclick="handler(3);">3</div>
<div onclick="handler(4);">4</div>
<div onclick="handler(5);">5</div>
<div onclick="handler(6);">6</div>
<div onclick="handler(7);">7</div>
<div onclick="handler(8);">8</div>
<div onclick="handler(9);">9</div>
</div>
Except that I don't want to write out onclick="handler(n);" a million times.
Any advice? and feel free to point to another resource that has the answer I need if there is one.
UPDATE
I'm looking for something compatible with older browsers as well. I'm going to have to not go for the bind function because according to mozilla docs, it works for IE 9+. I'm looking for something that works for IE 7+ as well as other browsers. I might have to go for event listeners if there is no other alternative.
You have a closure issue here (see JavaScript closure inside loops – simple practical example), a simple solution is to use bind to use the current value of n to be a parameter of the handler function
item[n].onclick=handler.bind(item[n],n);
U can use addEventListener and ID for find clicked element...
document.getElementById("Itemset").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a list item
var value_data = parseInt(e.target.textContent);
if(e.target && value_data > -1) {
alert("Malai test:: "+value_data);
//handler(value_data);
}
});
https://jsfiddle.net/malai/tydfx0az/
I found my answer here: https://bytes.com/topic/javascript/answers/652914-how-pass-parameter-using-dom-onclick-function-event
Instead of:
item[n].onclick=function(n){
handler(n);
}
I have to do:
item[n].onclick=new Function('handler('+n+')');
Funny thing is, the word function needs to be capitalized when making a new instance. It's awkward I have to go this route but it works in IE 7+
One alternative is :
function handler(){
alert(this.id);
}
function myFunction() {
var item=[];
collections=document.getElementById('Itemset');
for(n=0;n<10;n++){
item[n]=document.createElement('DIV');
item[n].innerHTML=n;
item[n].setAttribute("id","itemset"+n);
collections.appendChild(item[n]);
item[n].onclick=handler;
}
}
Insert dynamic ids to the elements and when you click on any element retrieve its id using this.id and do whatever you want to do with that value.
That's all.
Hope this helps.

Polymer - Get data-bound attribute value in repeating template

I'm having a bit of an issue here. I had a small amount of success with event.target.templateInstance.model.thing syntax to get the value of attributes from within a repeating template but I keep getting back undefined from this bit of code I have here:
downloadFunction: function (e) {
console.log("dl function clicked");
//get particular id of thing
var fu = e.target.templateInstance.model.s.soundId;
console.log(fu);
//^ returns "TypeError: Cannot read property 'soundId' of undefined"
}
And my repeating template is here:
<div layout horizontal wrap center center-justified>
<template repeat="{{s in carddata}}">
<sound-card image="{{s.imgurl}}"
quotetext="{{s.quote}}"
soundsrc="{{s.soundurl}}"
soundref="{{s.soundId}}"
downloadfunction="{{downloadFunction}}">
</sound-card>
</template>
</div>
Where carddata is just an array with my data in it. All of the values are generated fine so I know it's not an issue with my array. I'm just confused how exactly I'm supposed to target someting from within the repeating template? Am I calling it at the wrong time? Or am I messing up the syntax of the templateInstance bit?
If it matters, I'm trying to get it to work in an Android 4.4 webView using Apache Cordova. 4.4 webView doesn't appear to enjoy the shadowDOM terribly much.
Thanks!
edit: After some jiggery pokery with console logs, it appears that the sender value is referring to the div that I apply the on-click="{{downloadFunction}} to. Here's the template that I am repeating, if this provides any insight.
<div class="soundcard-container" vertical layout>
//can't target this one either on WebView 4.4, works on ChromeOS
<img src="{{image}}" on-tap="{{playAudio}}">
<div class="soundcard-bottom-container" horizontal layout center justified>
<span>{{quotetext}}</span>
//I have an 'a' tag for desktop browsers and the div tag is targeting my Android/iOS
//apps that I am exporting as a webView to using Apache Cordova. Webonly is hidden
//at the point where I'm trying to get my downloadfunction to work.
//console.log(sender) in my downloadfunction returns this div v
<div on-tap="{{downloadfunction}}" class="mobileonly"></div>
</div>
//just a hidden audio thing for web
<div style="display: none">
<audio id="{{soundref}}" src="{{soundsrc}}" controls preload="auto"></audio>
</div>
</div>
edit2 some console logs..
console.log(sender) and console.log(event.target) are both the same div that has the on-click event for my downloadFunction.. not sure if this should be the case.
console.log(e.target.templateInstance.model) returns my <sound-card> object, I believe like it should(?)
It's just when I add the specific .s.soundId that it's undefined. I'm not sure why it's unable to find it.. Maybe there's another way to get the specific soundId (or s.soundId rather) of that particular <sound-card> object?
I'll bet you want to refer to the "sender" of the event—not e.target. See the part about inSender at https://www.polymer-project.org/0.5/docs/polymer/polymer.html#declarative-event-mapping:
inSender: A reference to the node that declared the handler. This is
often different from inEvent.target (the lowest node that received the
event) and inEvent.currentTarget (the component processing the event),
so Polymer provides it directly.
This might fix it:
downloadFunction: function (e, detail, sender) {
console.log("dl function clicked");
//get particular id of thing
var fu = sender.templateInstance.model.s.soundId;
console.log(fu);
}
Alright I was able to fit this in a different way. I wasn't able to get e.target.templateInstance.model.s.soundId bit to work, so instead on the div that I call the event on (event.target) I gave it an attribute called data-soundid and passed it {{soundref}} from my original template and then where I repeat that template I simply made a function like so:
downloady: function (e) {
console.log(e.target.getAttribute('data-soundurl'));
}
Ta da! Very nice solution. Thanks to Eyal who suggested this to me in a previous question. It works like a charm. :-)
Here is working example of using templateInstance, with included selecting by dynamic ID: Plunk .
As for your code, can't tell why it's not working.
handleEvent: function(e, detail, sender) {
console.log('handleEvent');
console.log(sender.id);
//How to catch full_obj here,
//..as if first item is clicked: full_obj = {"firstName":"John", "lastName":"Doe"}
//console.log(e);
console.log(e.target.templateInstance.model.item.firstName);
//console.log(detail);
//console.log(sender);
this.instance_firstName = e.target.templateInstance.model.item.firstName;
this.instance_lastName = e.target.templateInstance.model.item.lastName;
//Selecting by dynamic ID
var clicked_element = this.shadowRoot.querySelector('#'+this.instance_firstName);
console.log('Selecting');
console.log(clicked_element);
//var second_element = sender.templateInstance.model.querySelector('my-second-element');
//var second_element = this.$.second_element;
}
Edit:
Event handling and data binding Docs

Hide div having variable dynamic ID

The div is a switch which gets a dynamic ID .
class name is impbtn , id is generated in variable this.impbtn6.id
HTML:
<div id="widget-id63032Candy_Eaten_importGoodsBtn" class="impbtn"></div>
There are two places hide is required - click and onload
In click event
document.getElementById(this.impbtn6.id).style.visibility="hidden";
works fine .
I cannot use Document.getelementbyID , as multiple form loads occur and button is not supposed to be hidden then .
So i trued using JQ to access css properties
This
jQuery('.impbtn, #this.impbtn6.id').css('visibility',"hidden");
works but makes all button in the class invisible . I want to make only this.expbtn6.id invisible not all ids under this class .
I have read each and every page available.Some things Iv unsuccessfully tried (Separately)
var vid= this.impbtn6.id;
jQuery("#"+ vid).visibility("hidden");
$('#vid .impbtn').css('visibility',"hidden")
var row2=$(".impbtn").find("div#"+vid);
row2.hide();
$('#vid .impbtn').css('visibility',"hidden");
$('div#vid').css('visibility',"hidden");
$('.impbtn', $("#div" + this.impbtn6.id)).css('visibility',"hidden");
$("#div"+ vid).css('visibility',"hidden");
$("#"+ vid).hide();
$('#vid').css('visibility',"hidden");
row = $('#' + vid);
row.css('visibility',"hidden");
I would highly appreciate a reply/comment.
your question is a little confusing as you say
document.getElementById(this.exportbtn6.id).style.visibility="visible";
works fine but this code shows the div, not hides it, and why cannot the same code be used to hide if you use it to show?
then your other snippet that supposedly works:
jQuery('.expbtn, #this.exportbtn6.id').css('visibility',"visible");
cannot work because #this.exportbtn6.id will not resolve to the variable's content inside the double quotes, so i am pretty sure this line will not do anything.
The way to do this correctly is
jQuery('#' + this.exportbtn6.id + '.expbtn').hide();
but i cannot tell for sure as the question is not clear. If my understanding of your question is correct, the above line will do the trick. Keep in mind that the value of "this" will differ based on context, so it maybe that you are referencing the wrong "this".
Try this
$('#this.exportbtn6.id').css('visibility','visible');
With jQuery:
$("#"+this.expbtn6.id).hide();
I hope it helps.

How to save an image's attribute id to a variable?

UPDATE - Sorry I tried to keep the code minimal, but looks like more detail is needed. I've created a non production jfiddle here with some notes to help explain what I'm trying to solve.
Hopefully this provides you with all details
http://jsfiddle.net/d86tm/5/
From looking at Google and SO nothing quite answers my answer...
After a user clicks an image I'd like to capture the attribute id assigned to the image and save it within a variable, something like
var friendRequestId = $(e.source).data("UserForBadge");
At the moment I have. But I'm not certain this is correct and its certainly returning an error
Uncaught ReferenceError: friendRequestId is not defined
Just looking for guidance/best practice example on how to complete this.
$(document).ready(function() {
$('.UserForBadge').css('cursor', 'pointer');
$('.UserForBadge').click(function(e) {
$(this).appendTo('friendRequestId');
// Nothing to worry about this part at the mo/////////
return false;
});
});
From what I understood by the question you wanted the id on the click of the image using jquery. Please find the fiddle
The code snippet used is:
e.target.id
if i understood correctly. your markup should be:
<img id="someId" onclick="imgClick(this)" />
and your js function:
function imgClick(sender){
var $img = $(this); //creates jQuery object from the DOM object
var id = $img.attr('id'); // extracts the id attribute
//your code...
}

Using fadein and append

I am loading JSON data to my page and using appendTo() but I am trying to fade in my results, any ideas?
$("#posts").fadeIn();
$(content).appendTo("#posts");
I saw that there is a difference between append and appendTo, on the documents.
I tried this as well:
$("#posts").append(content).fadeIn();
I got it, the above did the trick!
But I get "undefined" as one of my JSON values.
If you hide the content before you append it and chain the fadeIn method to that, you should get the effect that you're looking for.
// Create the DOM elements
$(content)
// Sets the style of the elements to "display:none"
.hide()
// Appends the hidden elements to the "posts" element
.appendTo('#posts')
// Fades the new content into view
.fadeIn();
I don't know if I fully understand the issue you're having, but something like this should work:
HTML:
<div id="posts">
<span id="post1">Something here</span>
</div>
Javascript:
var counter=0;
$.get("http://www.something/dir",
function(data){
$('#posts').append('<span style="display:none" id="post' + counter + ">" + data + "</span>" ) ;
$('#post' + counter).fadeIn();
counter += 1;
});
Basically you're wrapping each piece of the content (each "post") in a span, setting that span's display to none so it doesn't show up, and then fading it in.
This should solve your problem I think.
$('#content').prepend('<p>Hello!</p>');
$('#content').children(':first').fadeOut().fadeIn();
If you are doing append instead then you have to use the :last selector instead.
You have to be aware that the code doesn't execute linearly. The animated stuff can't be expected to halt code execution to do the animation and then return.
commmand();
animation();
command();
This is because the animation uses set timeout and other similar magic to do its job and settimeout is non-blocking.
This is why we have callback methods on animations to run when the animation is done ( to avoid changing something which doesn't exist yet )
command();
animation( ... function(){
command();
});
$(output_string.html).fadeIn().appendTo("#list");
assuming you have the following in the css defined:
.new {display:none}
and the javascript should be :
$('#content').append('<p class='new'>Hello!</p>');
$('#content').children('.new').fadeIn();
$('#content').children.removeClass('new');
$('#content').children('.new').hide();
First is convert received data to jQuery Object.
Second, hide it immediately.
Third, append it to a target node.
And, after this all, we can clearly use necessary animation, just like fadeIn :)
jNode = $("<div>first</div><div>second</div>");
jNode.hide();
$('#content').append(jNode);
jNode.fadeIn();
im have a exprensive,for this:
$("dt").append(tvlst.ddhtml);
$("dd:last").fadeIn(700);
I tried what you said did the trick but is not working.
it worked with the following code
$("div").append("content-to-add").hide().fadeIn();

Categories

Resources