I have this jQuery code
if (Meteor.isClient){
jQuery(document).ready(function(){
jQuery('#content .row > div').mouseenter( function(){
jQuery('#content .row div .edit').toggle();
});
jQuery('#content .row > div').mouseleave( function(){
jQuery('#content .row div .edit').toggle();
});
});
}
When I run my app this just doesn't work. If I put that into chrome console it works perfectly. What's the problem?
This also happened before with different code.
Your code adds callbacks to DOM elements that exist when your code is executed. However, Meteor will add stuff to the page later, when rendering templates. Here's how it should be done:
Option 1) Use Meteor events
Template.asdf.events({
'click .classname': function(e) {
...
}
});
Option 2) In the rare cases you need something that does not work in the previous way, put JQuery stuff in rendered callback:
Template.asdf.rendered = function(){
_.each(this.findAll('.classname'), function(element){
$(element).on('mouseenter', function(){...});
});
};
Option 3) In the ultra-rare cases when you need some special treatment for all the page, use JQuery live binding
Meteor.startup(function(){
$('#content .row > div').on('click', function(){...});
});
You can use meteor events.
For example use Meteor.startup(function () { instead of jQuery(document).ready(function(){
You must check up on http://docs.meteor.com/#eventmaps
may it be easy :)
Related
I'am trying to migrate from jquery 1.7 to 1.10 and the live function do not work anymore.
$("#detail_content").on("click", ".close", function (a) { // is ignored
//$("#detail_content .close").live("click", function (a) { //works fine with migrate
console.log("click");
});
the div.detail_content is loading later via ajax but the close button do not work anymore if i change from .live to .on
I think the delegation is missing.
any idea?
Looks like #detail_content also is an dynamic one, then try
$(document).on("click", "#detail_content .close", function (a) { // is ignored
//$("#detail_content .close").live("click", function (a) { //works fine with migrate
console.log("click");
});
You should use any closest static parent element (or body at last):
$("body").on("click", "#detail_content .close", function() { ... });
So if you have the markup like:
<body>
...
<div id="container">
...
<div id="detail_content"><button class="close">Close</button></div>
</div>
</body>
and #container is not replaced after Ajax call, then it is better to use:
$("#container").on("click", "#detail_content .close", function() { ... });
The .live() method is deprecated in jQuery 1.10 and above. Use .on() method to attach event handlers.
So you can use this code instead of .live()
$(document).on('click', '#detail_content .close', function(){
//your Code
});
I think this answer is useful for you and in this page you can see all deprecated method and it's useful for someone who want to migration from 1.7 to 1.10
VisioN, is it not the same to just use the following?
$(document).ready(function(){
$(".close").click(function(){
console.log("clicked");
}
});
Is there something about the code above that is slower or less efficient somehow?
I am quite new to javascript, but I am using it at my website. Last week I found a script that loads additional content to my page via jQuery. Everything was all right until I noticed that my other scripts stopped working because of that. For example I have a script that binds checkboxes:
<script>
$(document).ready(
function() {
$('.class_of_checkbox').click(
function() {
if(this.checked == true) {
$(".class_of other_checkbox").attr('checked', this.checked);
}
}
);
}
);
</script>
It is inline code. I have read that it could be caused by function ready(), which fires only when the DOM is loaded, but I am not sure how to solve this problem.
Dynamic elements loaded with ajax needs delegated event handlers :
$(document).ready(function() {
$(document).on('change', '.class_of_checkbox', function() {
if (this.checked)
$(".class_of other_checkbox").prop('checked', this.checked);
});
});
Replace the second document with the closest non-dynamic parent, use prop() for properties, and use the change event to capture changes in the state of a checkbox.
Use $.ajaxComplete to rebind your actions when the ajax call completes
http://api.jquery.com/ajaxComplete/
$(document).ajaxComplete(function() {
$('.class_of_checkbox').click(
function() {
if(this.checked == true) {
$(".class_of other_checkbox").attr('checked', this.checked);
}
}
);
});
So I generate some divs using this
document.getElementById('container').innerHTML += '<div class="colorBox" id="box'+i+'"></div>';
The problem I'm running into is that catching a hover event
$(".colorBox").hover(function(){
alert("!");
});
Won't work after doing that. Any thoughts?
EDIT:
To be more clear, check this out: http://graysonearle.com/test/16_t.html
I need to be able to have hover events happen after changing innerHTML that happen dynamically and many times. So like after changing the number of columns, the hover effect needs to work.
THANKS TO CHOSEN ANSWER:
For those in the future that might want to do something similar, my code looks like this now:
$(document).ready(function(){
document.body.onmousedown = function() {
++mouseDown;
}
document.body.onmouseup = function() {
--mouseDown;
}
$(document).on("mouseenter",".colorBox",function(){
if(mouseDown){
var clicked = $(this).attr("id");
var clicked = clicked.substring('box'.length);
next_color(clicked);
}
$(this).css("border-color","#ff0");
}).on("mouseleave", ".colorBox", function() {
$(this).css("border-color","#aaa");
});
$(document).on("click",".colorBox",function(){
var clicked = $(this).attr("id");
var clicked = clicked.substring('box'.length);
next_color(clicked);
});
});
whenever we update DOM from server side code or client side code.
For EX. DIV we are updating then it will not work with events we loaded before if we load that partial data.
so for this in document ready
code like this.
if you are using jquery 1.7+
then code like
$(document).on("hover",".colorBox",function(){
alert("Hi it will load after partial div update as well");
});
$(document).delegate(".colorBox","hover",function(){
alert("Hi it will load after partial div update as well");
});
and if you are using jquery 1.6 or less then that.
then use
$(".colorBox").live("hover",function(){
alert("Hi it will load after partial div update as well");
});
http://oscarotero.com/jquery/
If this helped you please mark as answer.
First, as you're using jQuery your first code could be simplified using the below function.
$('#container').append('<div class="colorBox" id="box'+i+'"></div>');
Second I think this is because you haven't declared the hover-off function.
$(".colorBox").hover(
function(){
alert("On");
}
);
Working Fiddle
You have to call your hover code AFTER injecting your divs. Jquery doesn't automatically listen to dom changes, so if you hook all your colorBoxes in $(document).ready(){...} and then insert a new div, nothing will ever happen.
So this works fine:
$(document).ready(function(){
for(i=0; i<5; i++) {
document.getElementById('container').innerHTML += '<div class="colorBox" id="box'+i+'"></div>';
}
$(".colorBox").hover(function(){
alert("!");
});
}
I need to trigger click events of "a" tags which are in "deletable" class. I saw some similar question in SO, but following code doesn't work for me. What i'm trying to do is to delete relevant <li> from <ul>.
$(document).ready(function () {
$('.deletable').live("click", function () {
alert("test"); // Debug
// Code to remove this <li> from <ul>
});
});
<form ...>
<ul>
<li>OneDelete</li>
<li>TwoDelete</li>
<li>ThreeDelete</li>
</ul>
</form>
I assume i'm using incorrect object hierarchy inside $('...') tag. But i don't have enough js/jquery/DOM knowladge to solve this problem. please help.
EDIT
Thanks for the answers, but none of them works for me. Actually i'm adding <li>s dynamically. There maybe a problem. Please check,
#sps - a listbox
#add - a button
#splist - another listbox
#remove - a button
$(document).ready(function() {
$('#add').click(function(e) {
var selectedOpts = $('#sps option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#splist').append($(selectedOpts).clone());
$('ul').append('<li>' + selectedOpts.text() + 'Remove' + '</li>');
e.preventDefault();
});
$('#remove').click(function(e) {
var selectedOpts = $('#splist option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$(selectedOpts).remove();
e.preventDefault();
});
});
The .live() method of jQuery has been deprecated. You can get similar functionality using $('body') and delegating to .deletable like I did in the following code:
$('body').on('click', '.deletable', function(e){
e.preventDefault();
// this is the li that was clicked
$(this).parent().remove();
});
The preventDefault method is used to keep the link from loading a new page should there be something targeted in the href attribute. If you keep the same HTML structure as you have in your example, then you can simply take the anchor element (this) and grab the parent, then remove it from the DOM.
It would be wise to, instead of using $('body'), target the container for the .deletable anchors, which, in this case, would be $('ul'). The function would look like this:
$('ul').on('click', '.deletable', function(e){
e.preventDefault();
// this is the li that was clicked
$(this).parent().remove();
});
Using $('body') means that every event on the page would have to be filtered to see if it originated from a .deletable anchor. By scoping it to the ul preceding your li's, you limit the number of times your function is called increasing performance.
Some things first: if you're using jQuery 1.9, the .live() function is not anymore supported. Versions prior, that particular function is deprecated anyway, so you shouldn't really use it.
That being said, your syntax looks about correct. So I'm assuming that it's your hierarchy inside the handler function that's incorrect.
Something like this should work if you're trying to delete the parent <li>:
$('.deletable').on('click', function (e) {
// since you're working with a link, it may be doing wonky default browser stuff
// so disable that for now
e.preventDefault();
// then we delete the parent li here:
$(this).parent('li').remove();
});
If you really want to make that into a delegate signature, something like this should work:
$('form').on('click', '.deletable', function (e) {
// same banana
});
you can use $('a.deletable') selector ... this finds the <a> with class deletable.
u can go through the on delegate events too.. here is the docs
try this
$('a.deletable').on("click",function(){
alert("test"); // Debug
// Code to remove this <li> from <ul>
$(this).parent("li").remove();
});
if in case your <li> is added dynamically..
$(document).on("click",'a.deletable',function(){ .... //even more better if u replace the document with closest elements to a.deletable ..like $(form)
live() is depricated..
$('a.deletable').live("click",function(){
alert("test"); // Debug
$(this).parent('li').remove();
});
I'm using some embed codes that insert HTML to the page dynamically and since I have to modify that dynamically inserted HTML, I want a jquery function to wait until the page has loaded, I tried delay but it doesnt seem to work.
So for example, the dynamically inserted HTMl has an element div#abc
and I have this jquery:
if ( $('#abc')[0] ) {
alert("yes");
}
the alert doesn't show up.
I'd appreciate any help
Thanks
$(window).load(function () {
....
});
If you have to wait for an iframe (and don't care about the assets, just the DOM) - try this:
$(document).ready(function() {
$('iframe').load(function() {
// do something
});
});
That is the purpose of jQuery's .ready() event:
$(document).ready(function() {
if ( $('#abc').length ) //If checking if the element exists, use .length
alert("yes");
});
Description: Specify a function to execute when the DOM is fully
loaded.
Using the jQuery.ready should be enough. Try this
$(document).ready(function(){
//your code here
});
or
$(function(){
});
which is a shortcut of the first.
The load() method was deprecated in jQuery version 1.8 and removed in version 3.0.
So you have to use -
$(window).on('load', function() {
// code here
});
Try this:
$(document).ready(function () {
if ( $('#abc')[0] ) {
alert("yes");
}
});
$(window).load(function () { ... }
can be enough but otherwise your embeded code (what ever that can be) might provide some callback functionality that you can make use of.
delay() should only be used to delay animations.
Generally, to handle my JQuery before or after page loads, will use:
jQuery(function($){
// use jQuery code here with $ formatting
// executes BEFORE page finishes loading
});
jQuery(document).ready(function($){
// use jQuery code here with $ formatting
// executes AFTER page finishes loading
});
Make sue you bind the event with dom load so it's there when trigger called.
This is how you do it. Hope this helps someone someday
$(window).bind("load", function() {
//enter code here
$("#dropdow-id").trigger('change');
});`