I am quite new to Jquery and need help trying to get a few events to run on the same page. I have two sections of events, one is a .get which passes data to a file and then displays retrieved data, this happens on page load. The second section is on click events which send and receive data when a button is clicked.
These events all work as needed, but if I have both sections on one page the on click events do not work. Below is the code I have and I hope someone knows how to get them all to work? Thanks
<script type="text/javascript">
$.get("/layout/standard/check.php", { url: "domain"}, function(data){
$("#content-area").html(data)
});
$(".discuss").click( function() {
$.post('/layout/standard/report-action.php', {form: "discuss"},function(data){
$(".message").html(data);
$(".message").show("slow");
});
});
$(".request").click( function() {
$.post('/layout/standard/report-action.php', {form: "request"},function(data){
$(".message").html(data);
$(".message").show("slow");
});
});
$(".report").click( function() {
$.post('/layout/standard/report-action.php', {form: "report"},function(data){
$(".message").html(data);
$(".message").show("slow");
});
});
</script>
I believe that I have found why it's not working, the onclick links are put on the page by the get event. It would appear that the buttons work if they're already on the page but not if they are inserted this way.
This doesn't make sense to me as the buttons are still acting as links with no problem...
Try delegation.. and putting your code inside a document.ready function
$(function() {
$.get("/layout/standard/check.php", {
url: "domain"
}, function(data) {
$("#content-area").html(data)
});
$("body").on('click','.discuss,.request,.report',function() {
$.post('/layout/standard/report-action.php', {
form: $(this).attr('class') //this is assuming you only have 1 class per element
}, function(data) {
$(".message").html(data);
$(".message").show("slow");
});
});
});
You might need to delegate the events if they are attached to content created dynamically. Try replacing:
$(".discuss").click( function() {
With:
$('body').on('click', '.discuss', function() {
And continue for all your events. You can replace the 'body' selector with another selector as long as it is always present in your document.
Related
I have an index page that contains the following events.
<div id="sub_page"></div>
$(document).ready(function () {
$("a.menu_navegacion_abrircaja").on('click', function (ev) {
ev.preventDefault();
var href = “nombrecontrollerEJ/view_ej";
$.post(href, function (data) {
$("#sub_page").html(data);
});
});
});
In it, when you click, load the html contents of subpages in the div sub_page.
In view view view_ej, I bring html code and also, jquery code. The Jquery code of the view that is added to the index div is as follows:
$(document).ready(function () {
$('#modal_establecer_turnos').on('hidden.bs.modal', function () {
alert("hello");
});
});
By clicking on the link that contains the class "menu_navegacion_abrircaja", I get the alert ("hello");
But it turns out that there is a problem, for every time I click on the link, the alert messages are repeated (alert ("hello");). For example, the first time I click on the link that contains the class menu_navegacion_abrircaja, it works fine showing the alert once, but then I click again on the same link it shows me the alert twice, then I do it for the third time, He shows me three times the alert, and so on.
I would like to know how to solve this problem.
Will there be any way to restart the events or handler of the jquery, as are the events click, change, "hidden.bs.modal", etc., in such a way that their repetition of the events is avoided?
I have seen the methods unbind (), bind (), off (), which might be the solution, but if so, how could you apply them?
Maybe you could try something like this in the jQuery code of your subpage:
$(document).ready(function () {
$('#modal_establecer_turnos').off('hidden.bs.modal');
$('#modal_establecer_turnos').on('hidden.bs.modal', function () {
alert(“hello”);
});
});
I'm working on a script to check if a file exists every 5s on onclick event. When it exists, I notify the client and reset the counter. First file check everything works fine, but when I check another file (click on another link with other data-file), it checks again both files and first file check is looping forever until I refresh the page. I tried everything I could think of, nothing worked. Please help!
var intervalCheck;
function isFileExists(file) {
$.ajax({
type: 'HEAD',
url: '/apps/'+file,
success: function() {
alert('found '+file);
clearInterval(intervalCheck);
},
error: function() {
}
});
}
$('#dialog').on('show.bs.modal', function(e) {
var file = $(e.relatedTarget).data('file');
$("a#checkfile").click(function() { intervalCheck = setInterval(function() { isFileExists(file); },5000); });
});
You must bind click event to only a#checkfile in clicked #dialog. Otherwise it will bind event to all a#checkfile elements. So when you open dialog for second time there will be 2 events on the a#checkfile link.
$(this).find('a#checkfile')
UPDATE
If there is one dialog contains multiple links, you can use jquery's one function for one-time events.
$('a#checkfile').one('click', function(){});
I've been having some trouble with this block of code, and I think I've finally narrowed the problem down. Here's the jQuery function...
$(document).ready(function(e) {
$('#formattingSection').load ('formattingdoc.html #formatting');
$('#loadFormatting').click(function() {
$('#formattingSection').load ('formattingdoc.html #formatting');
});
$('#loadSmileys').click(function() {
$('#formattingSection').load ('formattingdoc.html #smileys');
});
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
});
Basically, it works like this. The page loads, we load part of a doc via AJAX. There are four buttons on the page, each one loads a new section via AJAX. When you click #loadSmileys, it will load via AJAX several images and display them in the DIV.
I'm binding a click() event to those images... but what I've found is that since the images aren't on the page at load time, the click event never gets bound. When I strip all the code away and load the images without AJAX, the click binds okay.
So... my question here... is there a way to bind the click event to the images AFTER they are loaded via AJAX?
For reference... I did make a jsBin HERE, but it's basically just hard coding the images to that I can see it works without the AJAX stuff going on.
Try:
$("#formattingSection").on("click","div img",function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
As $.on attaches event handler to the parent and all events from children are delegated to the parent
Documentation
Yes, you totally can attach event handles to DOM nodes loaded on-the-fly. The trick is to use jQuery.get instead of .load. .get allows you to add an additional callback function that gets executed upon AJAX completion - the perfect place for you to add your $("#formattingSection div img") code. Here's what it would look like:
$('#loadSmileys').click(function() {
$('#formattingSection').get ({
url: "formattingdoc.html",
success: success
});
});
function success() {
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
}
$('#formattingSection').load ('formattingdoc.html #formatting', function( response, status, xhr ) {
loading_completed();
});
function loading_completed()
{
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
}
Try this
$('#loadSmileys').click(function() {
$('#formattingSection').load ('formattingdoc.html #smileys', function() {
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
});
});
You should use the 'on' method. This can apply click handlers to elements created after the on method is called.
e.g.
$("#formattingSection").on("click","div img",function() {
...
}
As imges are added, they will automatically get the click handler functionality.
This question I asked helps explain the difference: jquery use of bind vs on click
I am not sure what i am doing wrong here.i have a div and i want to open up a popup if user hover over that div section and want to close on mouseout. here is my code
<div class="topCart">
some data
</div>
this is my JQuery code
$(".topCart").mouseover(function() {
$.get('${rolloverPopupUrl}?bustcache=' + new Date().getTime(),
function(result) {
$('#viewCart').html(result);
refreshMiniCart();
});
$('#viewCart').slideDown('slow');
}).mouseout(function() {
$('#viewCart').slideUp('fast');
});
above code is not working nor its giving any Ajax call to fetch fresh data, while if i use following code
$(document).ready(function(){
$(".topCart").hover( function () {
$('#viewCart').html("");
$.get('${rolloverPopupUrl}?bustcache='+new Date().getTime(), function(result){
$('#viewCart').html(result);
refreshMiniCart();
});
if($('#viewCart').is(':hidden')){
$('#viewCart').slideDown('slow'); }
},
function () {
$('#viewCart').slideUp('fast');
});
});
this piece of code is working and its fetching data so i do not see use of document.ready
with my limited knowledge of Jquery i tried but not able to see the reason of not working of code
can any one point me my error?
Try having some basic structure and cleanliness (which is next to godliness) when typing your code, and spotting errors will be much easier:
$(function() {
$(".topCart").on({
mouseenter: function() {
var elem = $('#viewCart');
elem.empty();
$.get('${rolloverPopupUrl}?bustcache=' + new Date().getTime(), function(result) {
elem.html(result);
refreshMiniCart();
});
if (!elem.is(':visible')) elem.slideDown('slow');
},
mouseleave: function() {
$('#viewCart').slideUp('fast');
}
});
});
The first code does not work becuse not all DOM elements are downloaded when you set events. And it cause that result of $(".topCart") is empty. This not fire any erros, syntax is correct, problem is jQuery works with html, that are not completed.
$(document).ready(...)
or
$(function() {
// Handler for .ready() called.
});
$(document).ready(function() {
$(".topCart").mouseover(function() {
...
}
});
You need to use the document.ready before events can fire, after the document all DOM elements have loaded which you can be sure of, otherwise you're looking for an event which hasnt laoded into the DOM
Without the $(document).ready(), the first has not actually been bound to $('.topCart').
The second example, using the document ready gives a moment or time at which to bind the function to the hover event.
I have a case where a click handler is defined/assigned in one jQuery code block (file) and I want to trigger it from another click event defined/assigned in a different jQuery code block. How can I accomplish this?
The following code is a greatly simplified version of what I am trying to accomplish. The behavior I want to see is a JavaScript alert "Element One" when I click #Element2.
Example HTML:
<p id="Element1">Element One</p>
<p id="Element2">Element Two</p>
First jQuery code block:
$(document).ready(function() {
$('#Element1').click(function() {
alert('Element One');
});
});
Second jQuery code block:
$(document).ready(function() {
$('#Element2').click(function() {
$('#Element1').click();
});
});
UPDATE: My original example actually works. I was building upon my field hint jQuery UI Dialog solution, and didn't account for about the 'clickoutside' handler that I was using. Adding a check to for the second element in my 'clickoutside' handler allows the dialog to display.
You need to trigger a click when you click on the first element. You can use the trigger method for this.
function element1Hanlder () {
alert('Element One');
}
$(document).ready(function() {
$('#Element1').click(function() {
alert('Element One');
});
});
$(document).ready(function() {
$('#Element2').click(function() {
$('#Element1').trigger('click');
});
});
EDIT: This is based on JohnP's "trigger" suggestion (so you should choose him as the right answer)...
If I load this block from an external js file...
$(document).ready(function() {
$('#Element1').click(function () {
alert( $(this).text() );
});
});
Then load this in a script tag within the HTML itself...
$(document).ready(function() {
$('#Element2').click(function () {
$('#Element1').trigger('click');
});
});
Seems to be working as intended.