Swapping a CSS class on jQuery .load event - javascript

I have a list styled with CSS - standard stuff. The items within that feature jQuery .load to load the relevant info into another div. This works fine, however I also need to change the class in the list to reflect which item has been loaded. My existing code below, which will probably explain it better...
<ul class="inner-nav" id="tdlists">
<li class="active"><a onclick="$('##showlist').load('/lists/?List=#ListID#');">#ListName#</a></li>
<li><a onclick="$('##showlist').load('/lists/?List=#ListID#');">#ListName#</a></li>
<li><a onclick="$('##showlist').load('/lists/?List=#ListID#');">#ListName</a></li>
</ul>
The actual list is populated by a db query, however I've stripped that out as I don't believe it's relevant to the question and would only complicate matters!

You can take advantage of the this context set by jQuery for the load callback. For example:
$('#showlist').load('/lists/?List=#ListID#', function(){
$(this).addClass('loaded')
});
As a additional tip, is better if you use event delegation instead of writing the onclick attribute for each li tag:
$('#tdlists').on('click', 'li a', function () {
$('#showlist').load('/lists/?List=#ListID#', function(){
$(this).addClass('loaded')
});
}

The .load() event should have an event handler that will fire when the event is triggered, so you could set your class in there.
$('#showlist').load('/lists/?List=#ListID#',
function(){
//Add class or perform your logic here
$('#showlist').addClass(x););
}
);
.Load() | jQuery API

jQuery.load can be passed a callback method which runs on completion. This could then update the class on the parent.
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});

Related

Jquery mouse enter and mouse leave not working on li element

I am trying to use jquery mouse enter and mouse leave functions .
this is my code :
html :
<ul class="menuList bold">
<li id="tevee">
<span>test</span>
</li>
</ul>
jquery
$(function(){
$(".tevee").on("mouseenter",".menuList",hoverInFunction());
$(".tevee").mouseleave(hoverOutFunction("tevee"));
});
function hoverInFunction()
{
alert("hi")
}
function hoverOutFunction(variable)
{
alert("test");
}
https://jsfiddle.net/tejareddy/dndvsudh/ . this is my fiddle , they are not working instead they are triggering on page load and not every time when i hover on them .
Remove the ()
change
$(function(){
$("#tevee").on("mouseenter",".menuList",hoverInFunction());
});
to:
$(function(){
$("#tevee").on("mouseenter",".menuList",hoverInFunction)
});
or do it like this:
$("#tevee").on("mouseenter",".menuList",function(){
alert("hi")
}).on("mouseleave",".menuList", function(){
alert("test");
});
Firstly, your selector was incorrect for the ".on" call, secondly, you were using parenthesis when referring to a function (which in this case must be referred to as an object without the parenthesis).
$(function(){
$(".menuList").on("mouseenter","li",hoverInFunction);
$(".menuList").on("mouseleave","li",hoverOutFunction);
})
Please see the fixed version here
You may use event.data if you wish to pass parameters into the calls.
The original method of binding the event to the ID is not what .on is all about, it's best to bind to a higher-level object in the DOM (such as the actual menuList) and then write a selector which will affect the children on it. That way you get "delegated eventing" and any dynamically added items will still work the way you want them to.

DataTable can't get id element after page change

I am trying to make ajax call on focus for every text input, I can make is in first page( when document ready) but when I change page , javascript can't parse inputs because it wasn't created when document is ready. How can I fix it ?
jQuery(document).ready( function(){
jQuery('[id^=urun_sirasi-]').focus(function(){
event.preventDefault();
var urun_sirasi=jQuery(this).data('sira');
console.log(urun_sirasi);
jQuery('#urun_sirasi-'+urun_sirasi).bind('keyup',function(e)
{
console.log(jQuery("#urun_sirasi-"+urun_sirasi).val());
jQuery.ajax({
url:'../ajax.php',
data:'process=siralama&urun_id='+urun_sirasi+'&urun_sirasi='+jQuery.trim(jQuery("#urun_sirasi-"+urun_sirasi).val()),
success:function(e){
// e -> 1 ve ya0 geliyor.
console.log(e);
}
});
});
});
});
Thanks for your help.
This seems to a very common problem in the jQuery section. See the docs for .on() at http://api.jquery.com/on/, specifically the section about delegated events:
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time.
I use the following syntax in the doc ready that will create events for all future items with the "expand" class, should be able to be adjusted for you
$(document).on('click',"#myTable .expand", function(){
so yours should be something like this (maybe give your items a class rather than having an event to each element selector)
$(document).on('keyup',"#yourTable .urun_sirasi-key", function(){

jQuery won't bind click to underscore template using .on() for items added via function

I'm using underscore to create some elements and appending them to a div with jQuery.
At the bottom of the page I'm using jQuery's .on() to respond to clicks on the elements.
$('.pickup').on('click',
function(e) {
alert("hello");
}
);
Via some user interaction (in Google maps), I've got to add more elements to the div and want them to respond to clicks as well. For some reason they do not. I've pared it all down on jsfiddle:
http://jsfiddle.net/thunderrabbit/3GvPX/
When the page loads, note that clicking on the lines in output will alert('hello') via jQuery.
But click the [add] button and the new lines do not respond to clicks.
My HTML
<div id="unit_2225" class="pickup">
<span>Click me; I was here first</span>
</div>
<script type="text/template" id="unit-template">
<div class="unit-item">
<span class="pickup">
<span>click us (<%= unit_id %>) via underscore</span>
</span>
</div>
</script>
<div id="divID">
</div>
<button>add</button>
My Javascript
var addUnitToDiv = function(key,val) {
console.log(val);
var template = _.template($('#unit-template').html(),val);
$('#divID').append(template);
}
var unit_ids = [{unit_id:'hello'},
{unit_id:'click'},
{unit_id:'us'},
{unit_id:'too'},
{unit_id:112}];
$.each(unit_ids, addUnitToDiv);
var unit_pids = [{unit_id:'we'},
{unit_id:'wont'},
{unit_id:'respond'},
{unit_id:'to'},
{unit_id:'clicks'},
{unit_id:358}];
createMore = function() {
$.each(unit_pids, addUnitToDiv);
}
$('.pickup').on('click','span',function() {
alert("hello");
});
$('button').click(createMore);
I found a similarly worded question but couldn't figure out how to apply its answer here.
Instead of binding events directly to the elements, bind one event to their container element, and delegate it:
$("#divID").on("click", ".pickup", function () {
// Your event handler code
});
DEMO: http://jsfiddle.net/3GvPX/3/
In this case, the event handler is only executed for elements inside of the container #divID that have the class "pickup".
And in your scenario, the elements are being added to the element with an id of "divID". Thus, where the two selectors came from.
This is handy because, as you've found out, dynamically adding elements doesn't magically bind event handlers; event handlers bound normally with .on() are only executed (bound) on those present at the time of binding.
It could even help if you change the delegated selector to "span.pickup" (if you know the elements will always be a <span> like in your template), so that the DOM is filtered by the tag name first.
Reference:
http://api.jquery.com/on/#direct-and-delegated-events
Working demo http://jsfiddle.net/u2KjJ/
http://api.jquery.com/on/
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. You can attach the handler on the document level.
Hope it fits the need, :)
code try the code changed below
$(document).on('click','.pickup',function() {
alert("hello");
});

jQuery 1.7+ on(click..) doesn't work on <li> added dynamically

I have a dialog with a
<ul id="suggestions0">
<li id="suggestion0-0" class="suggestion">BLO</li>
<li id="suggestion0-1" class="suggestion">BLU</li>
<li id="suggestion0-2" class="suggestion">BLL</li>
<li id="suggestion0-3" class="suggestion">BOO</li>
<li id="suggestion0-4" class="suggestion">CLA</li>
</ul>
that I want to replace the content dynamically.
I change to ul content with this
$("#suggestions0").html("<li id='test0-1' class='suggestion'>BLO</li><li id='test0-2' class='suggestion'>BLO</li><li id='test0-3' class='suggestion'>BLO</li><li id='test0-4' class='suggestion'>BLO</li><li id='test0-5' class='suggestion'>BLO</li><li id='test0-6' class='suggestion'>BLO</li>");
What I want is when I click on one of these word, I want to do something, suppose an alert.
I try to do this
$(".suggestion").on("click", function() {
alert(this.id);
});
but the alert never appear.
here a sample that show the problem
http://jsfiddle.net/survivant/cyFxp/1/
in the sample, if you click on OK, it doesn't change to content, so if you click on a LI, it will works, but if you click on NOTOK, the events won't be received.
I'm using jQuery 1.7+, the live api is deprecated, or removed, it the APi suggest to use on().
You are not using on correctly. live is used to bind event handlers to the document to listen for events that bubble up from a specific selector, but by calling on explicitly on .suggestion, you will only attach the listeners to existing suggestions. So you need to use on to bind on an element that will always exist, and pass a selector to pick out the elements that get created dynamically.
// With live like this:
$('.suggestion').live('click', ...
// Is equivalent to this:
$(document).on('click', '.suggestion', ...
// Not this:
$('.suggestion').on('click', ...
In your case, rather than basing on off document, you can use your ul.
$("#suggestions0").on('click', '.suggestion', function(){
alert(this.id);
});
I found a solution, not sure that is the best one, but seems to work.
$("#suggestions").on("click","li", function() {
alert(this.id);
});
The script below only bind click event to DOMs current exist in the page.
$(".suggestion").on("click", function() {
alert(this.id);
});
To bind click event to all DOMs that are and will be created in the page. Bind the event to the document instead.
$(document).on("click", ".suggestion", function() {
alert(this.id);
});
See fiddler for codes.
Pass a selector to on() and it works like the old live():
$("#suggestions0").on("click", ".suggestion", function () { alert(this.id); });
See updated fiddle: http://jsfiddle.net/cyFxp/2/
suggestions is not a class but an id thus
it should not be
$(".suggestion").on("click", function() {
alert(this.id);
});
But like this
$("#suggestion").on("click", function() {
alert(this.id);
});
That is, instead of a dot you prefix it with a pound sign #.

After jQuery ajax load or update, I lose the mouseover event

After using .load to update my div, that is add item to my list, I used firebug and saw that the list was updated. However, I lost the mouseover event that worked when the page first loaded. In my script js I have:
// hide and show are css classes that display none and block respectively
function openList(){
$("#miniList").removeClass().addClass("show");
}
function closeList(){
$("#miniList").removeClass().addClass("hide");
}
...
$(document).ready(function() {
$("#miniList").mouseover(function() {
openList();
})
$("#miniList").mouseout(function() {
closeList();
})
});
function addItemToDiv(id, ref, num) {
$("#miniList").load("/list/ajax_updateList.jsp", {
'action' : 'additem',
'pid' : id,
'pref' : ref,
'qty' : num
});
}
Of course, this works fine the first time the page is loaded, but when I add item to the list, DOM is update but mouseover effects don't work any more.
Any thoughts are more than welcomed.
For DOM elments added dynimically you need to use the jquery .live() function.
Please go through the below link, I think that might fix your problem:
api.jquery.com/live
#ishwebdev, this is common problem we run , for all the DOM elments added after pageload like run time, we need to bind the events through live instead of regular bind
If you are using jquery 1.4 use below code:
// from jquery.com
$('give your selector here').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
// do something on mouseover
} else {
// do something on mouseout
}
});
#siri: thanks for the excellent answer, it worked for me right away. Here's my shopping cart dropdown example:
Before:
$("#cart-items").mouseenter(function(){
$('#cart-pulldown').show();
});
After:
$("#cart-items").live('mouseenter', function(){
$('#cart-pulldown').show();
});
With .live the event handling still works even after I change the underlying HTML via an Ajax call.
The selected answer no longer works for jquery 1.9+.
Instead, use "on" event, like
$( document ).on("keyup", "input.assets",function(event) {...
http://api.jquery.com/on/

Categories