jQuery's .on('click') not working - javascript

Templating is done in Jade, #name is putting a ID on the tag and .name puts a class
div#chatroom
div.row#chatcontainer.chatbg
div.large-12.columns
div.row
div.large-10.columns
h2#chatanchor.thin Party
i.fa.fa-minus-square-o
div.large-2.columns
i.fa.fa-users
div.row.chatbox
div.large-12.columns.chatwindow
div.mymessage
p Bill: Templating!
div.theirmessage
p.theirmessage Fredrickson: Templating!
div.row
div.large-12.columns.sitbottom
div.row.collapse
div.small-10.columns.large-10.sitbottom
input(type="text").sitbottom
div.small-2.columns.large-2.sitbottom
button(type="submit", class="button postfix sitbottom") Send
I have a simple chat window and when I click the h2 at the top it is supposed to minimize using this:
$('#chatanchor').on('click', function(e) {
console.log("Here");
});
The bind is called within document.ready in jQuery but doesn't work when I click it, but if I copy the code and paste it into the dev console and then click it, it works, so I'm not sure why it is not binding on page load.

It would seem that the element is being added after the DOM is ready, so your event isn't getting attached. Have it attach to any new elements that match your selector with the following:
$(document).on('click', '#chatanchor', function(e) {
console.log("Here");
});

Related

Running script after div added

Im using a plugin (Event Organiser Pro) that dynamically creates a div based on the input of a number field - basically it creates a duplicates the form fields depending on the number you enter in the input field.
I need to run some jQuery which is based on those form fields, but obviously cant run it until the div has been created.
How can i run the script once the div has been created? Is it possible to run script when div id has been created? Or something similar?
Yes, you can delegate the DOMNodeInserted event to the body.
function createDiv() {
$('<div />').addClass('test').appendTo($('body'));
}
$('body').on('DOMNodeInserted', '.test',function() {
alert('Created element .test');
})
$("button").on('click', function() {
createDiv();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create</button>
In the example above the click on the button simulates your other script creating the div.
To rewrite the code to work with your setup you can strip the click part out and delegate the event listener to your id:
$('body').on('DOMNodeInserted', '#your_element',function() {
yourFunction();
// call a function here or add your code here directly
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: This example won't work here because the element with that ID does not exist and neither does the yourFunction() function.

Loading several .php file into one div

Hello i have this code to load php file into div. Its working but i need load next file into this div.
<script type="text/javascript">
$(function() {
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().load(this.href).fadeToggle(1000);
});
});
</script>
<li><a class="load" href="zzz.php">zzz</a></li>
If i click "zzz" link loading file into my div (file table with images) i need hide this page and load next by click image.
UPDATE
Now working
<script type="text/javascript">
$(function() {
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().empty().load(this.href).fadeToggle(1000);
});
});
</script>
You just simply need to bind another click event to an image (or table body) that you load through load() function. However, you may experience some issue with your click not working, and heres why:
If you attach two click handlers, one for a.load and second for, let's say, .image than only the first event will actually get bind to its element, and the socond one won't be attached because, well, .image doesn't exist yet - not untill you load it.
You could expect, that once you php file content will get loaded (with .image elements in it), then clicking them will fire an action you have declared, but it won't - those .image's are new DOM elements and they missed an event binding procedure which was done only once when the DOM was created (or DOM was ready if you use $.(document).ready()).
So, in order to get those clicks to work you need to either attatch them on load() function callback, like so:
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().load(this.href, function(){
$(".image").on("click", function(e) {
$("#zaw").hide().load(/* load what you want */);
});
})
.fadeToggle(1000);
});
or insert .image click event binding inside php file you are loading or use some sort of delegation, for example:
$(document).on('click', '.image', function(){
/* do what you want */
});
which will make sure that even new, dynamically created DOM element will fire an action you want.

How to handle updating the navigation bar while using ajax

I have an AJAX implementation on my Wordpress install and I'm using the 'CSS and Javascript toolbox' plugin to apply additional Javascript code. I have also tried the following code in the header.php file in both the section and .
I'm using the standard 'Twenty Fourteen' theme and I'm referencing the primary navigation bar at the top. There are no subpages, just normal links.
http://twentyfourteendemo.wordpress.com/
The code I'm using, which I'm sure is the problem, is this
<script>
jQuery('ul.menu li').click(function(){
// Remove class on each item
jQuery('ul.menu li').removeClass('current-menu-item current_page_item');
// Add class for this one
jQuery(this).addClass('current_page_item current-menu-item');
})
</script>
I have also tried this
<script>
jQuery('ul.menu li').each(function() {
jQuery(this).removeClass('current-menu-item');
jQuery(this).removeClass('current_page_item');
});
jQuery(this).parents('li').addClass('current_page_item');
jQuery(this).parents('li').addClass('current-menu-item');
</script>
I don't know Javascript very well but this isn't doing anything. When a link is clicked, the 'highlighted' page on the navigation bar stays on the original page.
I have other code, that toggles the navigation bar on and off when a link is clicked (on mobile) and that works fine so the code is registering, just not working.
Does anyone know why this code isn't working? I've been stuck with this problem for days and I can't launch without this being fixed, I'd even throw some beer money to anyone with a solution
I cannot see your sample code in that website, to see if you code is in the body or head etc, but a couple of things you can try:
1 - You have not wrapped your code in a document ready event.
That means you may be running code against DOM elements before they exist, so the code does nothing.
This shortcut version of jQuery(document).ready() also provides a locally scoped $ variable so you can shorten your jQuery code:
<script>
jQuery(function($){
$('ul.menu li').click(function(){
// Remove class on each item
$('ul.menu li').removeClass('current-menu-item current_page_item');
// Add class for this one
$(this).addClass('current_page_item current-menu-item');
})
});
</script>
2 - If the menu items are added/classed-up after load (e.g. by a plugin), you need to use delegated event handlers:
e.g.
<script>
jQuery(function($){
$(document).on('click', 'ul.menu li', function(){
// Remove class on each item
$('ul.menu li').removeClass('current-menu-item current_page_item');
// Add class for this one
$(this).addClass('current_page_item current-menu-item');
})
});
</script>
This works by listening for the event bubbling up to a non-changing ancestor element, then applying a jQuery element selector, then applying your function to any selected elements that caused the event.
Notes: The fallback element for delegated events should always be document and not 'body' as 'body' has some bugs (related to styling) that can cause events not to trigger. You should however target the nearest non-changing ancestor to be most efficient.
Note: The second option is generally the best way to code event handlers for e group of controls, as it only adds a single handler to the DOM.
Update:
As predicted, the JS code was in the header, so needed wrapping in a document ready event handler.
Also, the actual website uses a menu like this: <ul id="menu-pages" class="nav-menu"> so the selector for the menu items should be ul.nav-menu li or #menu-pages li and not ul.menu li.
e.g
<script>
jQuery(function($){
$(document).on('click', 'ul.nav-menu li', function(){
// Remove class on each item
$('ul.nav-menu li').removeClass('current-menu-item current_page_item');
// Add class for this one
$(this).addClass('current_page_item current-menu-item');
})
});
</script>

JQuery does not determine the div class which is printed from ajax

I have html elements that printed in html page using smarty engine , then printed from jquery
the html which is printed from smarty is
<div id="broadcastsXXX" class="broadcast orginal-broadcast highlightedbroadcast">
<i class="dogears"></i>
<div class="content">
...
...
</div>
</div>
and the html which is printed from jquery is the same html code which is printed comming from smarty template as shown above.
I want to remove the css class "highlightedbroadcast" when someone clicked on the div which has the class "content" as shown above
so I do the jquery code:
$(document).ready(function() {
$('.content').click(function() {
$(this).parent().removeClass("highlightedbroadcast");
var broadcastid = ($(this).parent().attr("id"));
});
});
The function is changing the clicked div parent and remove the class highlightedbroadcast.
when the user clicked on the .content div that is printed from smarty template when page loas its remove the highlightedbroadcast css class without any problem. but if the user clicked on the div .content which has been printed from ajax it will not remove the class and do nothing.
I try to add alert('hi') to the function and it also says hi when the user clicked on the .content div which is comes from smarty and do noting when the user clicked on the div which is printed from ajax.
note that the broadcastsXXX is dynamic as broadcasts123 broadcasts124 .. etc
and this is a real example http://jsfiddle.net/samshannaq/FUK5Z/2/
so is there any solution for this?
.click() will only add event handlers to the current DOM.
If you want jQuery events to also apply to any HTML that is subsequently loaded via AJAX, you need to use the .on() event handler rather than .click():
$(document).ready(function() {
$('body').on('click', '.content', function() {
$(this).parent().removeClass("highlightedbroadcast");
var broadcastid = ($(this).parent().attr("id"));
});
});
Either that, or you need to add the click events to HTML that is loaded via AJAX after every AJAX call.
I think you should use 'live', while not just 'bind' or 'click' . When document is ready, the div.content is not rendered at all ( they are rendered through ajax response. ). so change your code to
$(document).ready(function() {
$('.content').live('click',function() {
$(this).parent().removeClass("highlightedbroadcast");
var broadcastid = ($(this).parent().attr("id"));
});
});
may work.

Container hierarchy access for jQuery elements

JQM elements on physical page:
#page_test1
button changing page to #page_test2
#page_test2
div #place to put something programmatically
to put button inside #place container I wrote the following (working) code:
$(document).on('pagebeforeshow', '#page_test2', function(event) {
$('#place').empty();
$('#place').append('Dynamic button inserted by JavaScript');
$('#place').trigger('create');
});
Ok, but when I take an attempt to move .on body to script level (directly under script tag) code inside become wrong because of context loose:
$(document).on('pagebeforeshow', '#page_test2', function(event) {
addButton(); // Attempt to move widget manipulation up
});
// Widget manipulation not changed but moved outside (level up) .on
// Not working
function addButton() {
$('#place').empty();
$('#place').append('Dynamic button inserted by JavaScript');
$('#place').trigger('create');
}
How to access JQM elements from different levels of JQM hierarchy and outside of it?
Guess it is very basic for JQM / Ajax so I will very thankful to take URL with common information.
To access an dynamically through code outside the target page, use the the following:
$(document).on(event, '.selector', function() { });
To access an dynamically through code inside the target page, use the the following:
$('.selector').on(event, function() { });

Categories

Resources