How to preprocess the HTML content using Jquery "ON"? - javascript

I have very simple jQuery Accordion, it is working fine, now the issues are if i load the accordion content dynamically either from DB or from JSON to page, It is not working, because there is no information to DOM to understand the class or ID which newly injected. so i am trying to use Jquery ON instead live or delegate to capture the injected elements. my sample code is..
jQuery("#header").on("click", function () {
.... my accordion code here
});
but jquery "on" will trigger on any event like click or something, so how to process the accordion html content to keep open in initial level and do further click.
How is this possible? i couldn't fine any solution

Check this: http://jsfiddle.net/RMBpt/
What i added:
var isActive = $(this).is('.on');
if(!isActive) { .. if active, it shouldn't collapse? }
//First element should be active, needs to be after the hide()
$('.accordionButton:first').addClass('on').next().slideDown('normal');
Try using it like this:
$("#wrapper").on("click", ".accordionButton", function(event){
//Your accordian code here
});

Related

jQuery Toggling next row in dynamically created table with dynamically created button

I have a jQuery dynamically created table that appends data from json file.
one of the rows of the table is a row of buttons that are appended into a row variable that is appended into the table:
var like = $("<a href='index.html'><button class='likeBtn'>like</button></a>");
var comment = $("<a href='index.html'><button class='comBtn'>comment</button></a>");
var toggle = $("<a href='index.html'><button class='togBtn'>show/hide comments</button></a>");
row3.append(like).buttonset();
row3.append(comment).buttonset();
row3.append(toggle).buttonset();
$("#table").append(row3);
now I need to toggle the row below in the table when clicking the toggle button.
this is my onclick function:
$(function(){
alert("in");
$('.togBtn').click(function() {
alert("in2");
$(this).closest('tr').toggle();
});
});
when I put alerts inside the click function I don't see them, I do see alerts from the function that holds the click function. for example- I see "in" but I don't see "in2".
and of course the row is not toggled.
commentRow is the class of the row that needs to be toggled.
I tried lots of options like-
$("#table").closest('.commentRow').toggle();
also with next() , All(), and many others and I can't get it to work!!!
please - your thoughts on this.
All help will be much appreciated!
It's due to the dynamically generated content, try that:
$(document).on('click','.togBtn',function(e) {
alert("in2");
$(this).closest('tr').toggle();
// or return false; // it does both preventDefault & stopPropagation.
});
This is called event delegation. This technique is only used when you have generated dynamic DOM nodes like as you are doing in your code.
So, in this case all the events were bound when page was initially loaded and the elements are generated after page load, due to that browser didn't registered any event for those elements because of unavailablity. In this case event has to be delegated to the static parent node or to the document itself because it is always available.
Syntax for event delegation using .on() method:
$(staticParent).on(event, selector, cb);
With the help of the answers posted here I found a solution that works:
$(document).on('click','.togBtn',function(e) {
alert("in2");
e.preventDefault();
$(this).parents("tr").next().slideToggle();
// or return false; // it does both preventDefault & stopPropagation.
});
Thanks all for your help!

jQuery select links that don't have any JS events linked to them for PJAX to work on links only?

I have a basic shopping website built on WordPress and Woocommerce. Naturally, a lot of the buttons and links have Javascript functions preventing the default behavior of going to the link and doing something else instead. Unfortunately, if I set PJAX to select all $('a') elements, then the AJAX functions (or javascript such as even dropdown) functions would seize to work properly and PJAX would take over and refresh the page.
For example, if I would click on a Bootstrap dropdown link, it would go to the link rather than open the dropdown.
I want to know if there's a way to select elements (using jQuery) that only go to their links and have no JS events listening to them.
Try this demonstration and let me know if it works for your scenario.
HTML:
Link 1
Link 2
Link 3
Link 4
<br>
<br>
<button id="test">Which links have no jQuery click event bound?</button>
jQuery:
$(function() {
// Assign handler to links with class 'link-with-handler'
$('.link-with-handler').click(function() { alert('handled'); });
// Test function
$('#test').click(function(){
// Get all links
var links = $('a');
// Iterate through links testing each one for the event handler
$.each(links, function( index, value ) {
var ev = $._data(value, 'events');
if (!ev || !ev.click) {
alert(value.innerText + ' has no jQuery click handler bound to it.');
}
});
});
});
http://jsfiddle.net/goq7a6bn/2/

Set a JQuery function on the button HTML declaration

I'm trying to use AJAX loading a set of sucessive pages in a main page, as I show you in the next picture:
I learned (thanks to this community!) to call other pages' content, by assigning the load() function to the onclick event of a button, like this:
$(document).ready(function() {
$('#btn').click(function() {
$('#result').load('./poi-data-no-heading.html');
});
});
But what if I have one button with id="btn" on every page? The functionality of any button with that id will be the same always, because (I think) the document.ready is not triggered when I use the load() method, so it's never replaced with new functionality.
E.g. initial functionality should be navigate from page 1 to page 2, and when page 2 is loaded, the functionality should be to navigate from page 2 to page 3.
As Js developer, I would do the following:
<!-- In the HTML file -->
<button id="btn" onclick="loadContent()">Load</button>
<div id="result"></div>
/* In the JS file */
function loadContent(){
/*the code to retrieve content*/
$('#result').load('http://fiddle.jshell.net/webdevem/JfcJp/show/');
}
This way I could assign the functionality to every button, no matter what's the ID or if the document.ready is triggered. But mixing Js with JQuery is not an option... So, how do you think I should manage to do something similar with JQuery?
Thanks in advance.
P/d: Here is a useful fiddle I used to try ideas: http://jsfiddle.net/gal007/vkcug7t7/1/
You could use the on() event from jQuery, which can listen for events on elements dynamically rendered (you can't do that with the click() method). So in this case you have to listen to the event on a parent element, one that doesn't change with the load method. On that button, use an HTML5 data-* attribute to define the id that you wish to load.
HTML:
<btn id="result" data-load-id="1">Load</btn>
Javascript:
$('#container').on('click', '#result', function() {
var id_to_load = $(this).data('load-id');
load('/url?' + id_to_load);
});
I've updated your fiddle : jsfiddle

Why "opener.$(document).trigger('custom')" is not working?

I want to implement simple pub/sub pattern with jQuery.
So I add some code like this on parent page:
Parent page:
$(document).bind('custom', function() { ... });
And it's working fine when I trigger on same page like this:
Same Page:
$(document).trigger('custom'); // Working.
But when I trigger this on popup page, it's not working.
Popup page:
opener.$(document).trigger('custom'); // Not working.
$(opener.document).trigger('custom'); // Not working.
If I bind event to <body> element, it works find.
Parent Page:
$('body').bind('custom', function() { ... });
Popup Page:
opener.$('body').trigger('custom'); // Working.
Why binding to document is not working on Popup?
As #11684 said, the answer to make it work is:
opener.$(opener.document).trigger('custom');
The #Rory's answer:
$(opener.document).trigger('custom');
is not working because the popup's $ doesn't have the event handler of opener.document.
And this one:
opener.$(document).trigger('custom');
is not working because the document is popup's document so it's different from the opener.document.
And lastly,
opener.$('body').trigger('custom');
is working because the opener's $ has event handler and the argument(body) is just string(not a object like document).
You need to place the whole opener.document in to a jQuery object. Try this in the popup:
$(opener.document).trigger('custom');

jquery related question

i am modifying the inner html through javascript, and the inner html involves a button
but when i put in the jquery code to run on the button click event it fails to do so ..
sorry but im a newb when it comes to javascript
content im adding into the html ..
function add()
{
var val=document.getElementById("ans").value;
document.getElementById("answers").innerHTML+="<tr><td>"+val+"<br/><p align=\"right\"><button class=\"replyb\">replies</button></p>"+"</td></tr>";
document.getElementById("ans").value="";
}
jquery code ...
enter code here
At a guess, because we don't have your jQuery, I would say you need to use .live() instead of .click() when you change the HTML the button will be NEW to the DOM.
When you apply your jQuery code, it adds any calls like .click() to any DOM item, when the page loads. So any NEW element doesn't have a .click() handler added to them.
Do solve this, you can change your .click():
$('#someitem').click(function() {
.....
});
To something like this:
$('#someitem').live('click', function() {
.....
}
Add the following in your page at some place and it will handle clicks to all .replyb buttons whether you add them with javascript at any time, or not.
$(function(){
$('button.replyb').live('click', function(){
alert('clicked on button');
});
});
have a look at jquery .live() method

Categories