I have this object I need to create with JS and later on I need to do an on hover do something statement...And because this div is created clientside later, my hover statement doesn't apply...So my question is, can I somehow live create this just like I was to use jquery.live() but with plain JS?
var parentContainer = document.getElementById('box');
var someContainer = document.createElement("div");
someContainer.className = "fun";
parentContainer.appendChild(someContainer);
jQuery("#box").hover(function() {
jQuery("#box .fun").fadeIn('fast');
});
So this obviously does not work because of the live bind issue...
Thanks for the help.
What needs to be live is the hover function, not the object.
Live means the event handler is placed at the root of the DOM tree, and if it matches your selector it will trigger.
Read more about how .live() works in jQuery's API documentation.
Related
I have multiple items with the same class I want to change when the user hovers over them.
I could add the events like this in the HTML but this seems rather unpretty:
<div class="video-item" onmouseenter="overVideoStart(this)"></div>
The JavaScript looks like this:
function overVideoStart(element)
{
element.className += " video-item-hover";
...
}
Is there a more good looking way to do this? I wish to leave the onmouseenter attribute away and instead have it defined in the JavaScript file. There is a way to do this for single items but I haven't found a way to do this for classes. I'm sorry if this is a total noob question but this is my first time I'm working with JavaScript.
You can use addEventListener to add events to elements in JS.
To add event listeners to multiple elements you would need to capture all the elements first and loop through them and set each one to have a listener.
var elements = document.querySelectorAll('.video-item');
for(var i=0; i<elements.length; i++){
elements[i].addEventListener("mouseenter",mouseEnter);
}
function mouseEnter(e){
//e will refer to the event object
//you can refer to the element with keyword "this"
}
If you include a library like jQuery you can shorten the code a little as it will do the looping and other work behind the scenes
jQuery('.video-item').mouseenter(mouseEnter);
function mouseEnter(e){
//e will refer to the event object
//you can refer to the element with keyword "this"
}
You can add jQuery to your webpage, and use it's css selector like queries to set at once callbacks for elements that match the query.
For example in your case:
jQuery(".video-item").mouseenter(function(event) {
// handle the mouse enter
});
Or, if the matching elements can change over time - e.g. via ajax calls - you can use the more powerful .on() function.
I have been searching this on internet, I have found some answers which were helpful like but they were not enough to solve my problem (e.g.
Similar Problem but no solution provided for my problem)
I am using JRate plugin, I am adding a div inside a div using jQuery. The problem is that when I add it using jQuery and use the JRate Functions then they are not working. But they are working without appending a new div.
I know how to make it work. I will have to use $(document) but I dont know how to use it with this code.
Here is HTML
<div class="jRate"></div>
Here is my Jquery
$(".jRate").jRate({
onSet: function(rating) {
alert(rating);
}
});
Here is my appending code
var divjRate = "<div class='jRate'></div>";
$(divjRate).appendTo('.fb-jRate');
Can any one tell me how can I use $(document) here or any other alternative solution you have.
You need to append the html element first so that it is registered in the DOM. Then, you can call jRate on it
var divjRate = "<div><div class='jRate'></div></div>";
// Append new element to container of choice
$(divjRate).appendTo('.fb-jRate');
// Use plugin on new element
$('.jRate').jRate({
onSet: function(rating) {
alert(rating);
}
});
The solution you have linked applies to binding event listeners, which is not the case with a typical jQuery plugin that usually involves DOM replacement and other things.
You will need to apply the method to newly added DOM elements. The DOM mutation event specification is deprecated due to performance issues, and it is not realistic to expect the browser to keep track of all changes (and what kind of changes) happening in the DOM.
For example, if you're adding new content with an AJAX call, you can apply the method to newly added content within the jqXHR.done() function.
Update: OP provided with some code, so I have adding a way to initialize the plugin for newly added DOM element:
// Declare new element
var divjRate = "<div><div class='jRate'></div></div>";
// Use plugin on new element
$(divjRate).find('.jRate').jRate({
onSet: function(rating) {
alert(rating);
}
});
// Append new element to container of choice
$(divjRate).appendTo('.fb-jRate');
Well, out of the box, jQuery does not have support for selecting nodes inside webcomponent(s). (probably because document.querySelector() does not work for shadow DOM (nor it should, by definition)).
Our previous codebase was somewhat dependent on jQuery and many of the devs do not want to let go of the simplicity of $(...) selection. So, I wrapped up this quick and dirty trick.
window.$$ = function (that, selector) {
return $(that.shadowRoot.querySelectorAll(selector));
}
Usage (inside a lifetime callback or whenever the host node can be accessed):
jqel = $$(this, '.myClass'); // this has reference to the host
The question is, is there a better way to go about this?
i have created a jquery-polymer plugin that has a lot of functions that may help you dealing with polymer shadow dom
https://github.com/digital-flowers/jquery-polymer
to select any element inside a polymer element lets say
<my-button id='button1'></my-button>
first you need to get the button shadow root using
$("#button1").getShadowRoot()
or
$("#button1").shadow()
this will return the button shadow root as jquery object then you can select anything inside it for example
$("#button1").shadow().find("ul > li:first")
cheers ;)
As far as I know Jquery permits passing context as parameter JqueryContext, so the proper way would be:
$('selector',context)
As an example:
var component1 = document.querySelector('qr-code');
// Find some img inside qr-code component
var img1 = $('img',component1)
I'm semi-new to Javascript/jQuery so apologies in advanced if I'm missing something basic. I have a function that is triggered whenever a user types in an element with a specific class.
$('.relevantClass').keyup(function(){
//code...
});
Now this function may end up, depending on the situation, creating a good deal of new HTML including new instances of relevantClass through the .append() method.
var newHTML = <div class='relevantclass'>Content...</div>;
$('#wrapper').append(newHtml);
However, the jQuery selector does not seem to detect and execute the function when a user types in the newly created relevantClasses. I've checked the newly created Html and it has the correct class tags and old instances of the relevant class due work.
I'm guessing this has something to do with .append(); messing with the DOM and I need someway to "refresh" the selector and let it do its jQuery thing researching the DOM to find the new classes. Any thoughts on how to do this? Is there some jQuery method I can't find?
You have to use on() to attach events that work on dynamic content:
var $parent = $("selector"); //the element you're appending .relevantClass to
$parent.on("keyup",".relevantClass",function(){
//code...
});
Keep in mind that to work with dynamic content, you have to attach the event to relevantClass's closest parent that exists on page load.
Some people use body, but you should get used to using parent elements as close as you can get to the dynamic content. This is so that event delegation occurs on a smaller scale.
More info on on() here.
Also, I hope that newhtml variable is wrapped in quotes.
$('.relevantClass').on('keyup', function(){
//code...
});
Try something like
$('body').on('keyup', '.relevantClass', function() { ... }
The idea is that you use an existing root element and use your class selector as a filter. See the examples here.
So, say I have selected, in JQuery, a singular DOM div.
I then proceed to create a new DIV like so:
var DIV = $("<div>Hello, world</div>");
After that, I attempt to place that DIV inside the original one like so:
$(OriginalDiv).append(DIV);
Okay, that works.
Now I want to edit DIV further.
Calls to .click, .html, .addClass, (And likely more) do not work!
Okay, instead I do:
var OriginalDiv = $("someSelector");
var DIV = $("<div>Hello, world</div>");
DIV = $(OriginalDiv).append(DIV);
That appears to work at first; However, instead, it sets DIV to reference the same DOM object as OriginalDiv and NOT the newly appended DOM object. Naturally, this does not allow me to edit DIV.
So, then, I try two more methods:
var OriginalDiv = $("someSelector");
var DIV = $("<div>Hello, world</div>");
$(DIV).appendTo(OriginalDiv);
and
var OriginalDiv = $("someSelector");
var DIV = $("<div>Hello, world</div>");
DIV = $(DIV).appendTo(OriginalDiv);
Not even these work.
If I haven't done a very good job explaining, here is my exact dilemma
I am trying to create a DOM object in jquery, then append it to another DOM object using jquery. The problem is, once it gets appended, there seems to be no way for me to directly access it without using somethign like .children.
I'd like very much to be directly returned somewhere along in that process a reference to the DOM object which I am appending. As in the one that actually gets appended.
I'm not sure how to do this in JQuery. Anybody know a solution?
Thanks
--G
Yes, append won't work as it returns a reference to the element the new element was appended to. jQuery supports method chaining, so this should work easily:
$("<div>Hello, world</div>")
.click(function() {
// something
})
.appendTo('someSelector');
But even
var $ele = $("<div>Hello, world</div>").appendTo('someSelector');
will work. appendTo returns a reference to the element which was appended. If this does not work for you, you have your problem elsewhere.
Comments on your code: This is not your problem, however it is important for you to know what is going on here.
This part
var OriginalDiv = $("someSelector");
var DIV = $("<div>Hello, world</div>");
$(DIV).appendTo(OriginalDiv);
is the same as
$($("<div>Hello, world</div>")).appendTo($("someSelector"));
You see, you have a nested call to jQuery, because DIV is already a jQuery object. There is no need to pass it again to jQuery.
You can also pass a selector directly to appendTo.
you could try this;
var DIV = document.createElement('div');
then you can use;
$(div).html('Test!');
or what ever you want to use with.
You don't have to get anything back from the DOM. Once you create the element with jQuery, you already have a reference to the DOM element. Inserting it into the document does not do anything special.
// this will create the DOM element, and the jQuery
// object wrapping that newly created DOM object
// is assigned to DIV.
var DIV = $("<div>Hello, world</div>");
// Don't worry about getting a return value from this
// append() call. What we need is already available inside
// the variable DIV.
$(OriginalDiv).append(DIV);
// continue using DIV as you normally would. It is referring
// to the same DOM object that was just appended to the document.
DIV.addClass('green');