Jquery simple ajax - Insert html - javascript

When a div is opnened i want to load html content into it via ajax. This is the code im working with:
http://jsfiddle.net/uhEgG/2/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle();
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
The code I think I need is this:
$.ajaxSetup ({
cache: false
});
var ajax_load = "Loading...";
var loadUrl = "www.test.com/site.html";
$("#load_basic").click(function(){
$("#country_slide").html(ajax_load).load(loadUrl);
})
How can I make it work to make it load up when the div is opened by the code above, firstly because it is setup for a click function not a toggle function, and second, because the toggle doesn't seem to be able to distinguish if the div is open or not.

to make it load up when the div is opened by the code above
$("#country_slide").slideToggle(function(){
if($(this).is(':visible')){
$("#country_slide").html(ajax_load).load(loadUrl);
}
});

Try to delegate the events.. Looks like the element is not yet available in the DOm when the event is bound
Replace
$('#country').click(function () {
with
$(staticContainer).on('click', '#country', function () {
staticContainer is the element which is already in your DOM when the event is bound and the ancestor of country

Either store the slide state in a variable or in a data attribute liek this:
<div id="country_slide" data-state="1">
And make something like this:
$('#country').click(function () {
$("#country_slide").slideToggle();
if ($("#country_slide").attr("data-state") == 0)
$("#country_slide").html(ajax_load).load(loadUrl);
});

Related

flipping between register and login form

<script>
$(document).ready(function(){
$("#register_link").click(function()
{
$("#login_or_register").empty();
$("#login_or_register").load("register_form.php");
});
$("#login_link").click(function()
{
$("#login_or_register").empty();
$("#login_or_register").load("login_form.php");
});
});
</script>
This is my jquery code for flipping between login and register forms.
Initially the page contains the login form and a link to load the register form. It works the first time to load the register form and a link to load the login form. But it doesn't work after that. It doesn't change from register to login form. How to rectify this?
This is because the listeners are only set on existing elements. When you load something using Ajax (jQuery.load()), there will be no listeners on those new elements. You can fix it by re-initializing the click listeners, after the new content is loaded, like this:
<script>
function listenToClick() {
$("#register_link").click(function() {
$("#login_or_register").empty();
$("#login_or_register").load("register_form.php", function() {
listenToClick();
});
});
$("#login_link").click(function() {
$("#login_or_register").empty();
$("#login_or_register").load("login_form.php", function() {
listenToClick();
});
});
}
$(document).ready(function(){
listenToClick();
});
</script>
An even better option would be to listen to the click event using the on function. The on function also listens to future elements (the elements created by jQuery.load()).
<script>
$(document).ready(function() {
$("#register_link").on('click', function() {
$("#login_or_register").empty();
$("#login_or_register").load("register_form.php");
});
$("#login_link").on('click', function() {
$("#login_or_register").empty();
$("#login_or_register").load("login_form.php");
});
});
</script>
You can use .on() to delegate the events like this:
$(document).ready(function(){
$(document).on('click', "#register_link, #login_link", function() {
$("#login_or_register")
.empty()
.load($(this).is('#register_link') ? "register_form.php" : "login_form.php");
});
});
Use event delegation to account for elements that don't exist at run time that may be added to the dom later:
$(document).on('click', '#register_link, #login_link').click(function () {
var url = $(this).is('#login_link') ? "login_form.php" :"register_form.php" ;
$("#login_or_register").empty().load(url);
});

Document ready not hit on page load, but it works using Developer Tools Console

On Ajax Success, li element is appended to ul.
$.ajax({
..
success: function (response) {
response.data.forEach(function (x) {
$("#ulMain").append('<li class="liSub">' + x + '</li>');
}
});
It creates sth like this:
<ul>
<li class="liSub">ABC</li>
<li class="liSub">BCF</li>
</ul>
I want the dynamically added li elements to fire an alertbox on click.
But the code below is not being hit.
$(document).ready(function () {
$(".liSub").on("click", function () {
alert("Fired");
});
});
Interestingly, If I run the document.ready section of the code using F12 - Console, it works. What stops it run normally, and lets it run through console?
You missed . prefix for class and use event delgation for created dynamic dom elements
$("ul").on("click", '.liSub', function () {
alert("Fired");
});
Since it is an element loaded dynamically, try delegating it:
$(document).ready(function () {
$("body").on("click",".liSub", function () {
alert("Fired");
});
});
It is because when your page is ready, the ajax call is not finished. You can try this :
$(document).ready(function () {
$("#ulMain").on("click",".liSub", function () {
alert("Fired");
});
});
It will bind the click to the #ulMain which exists at the execution and will delegate the event to .liSub at the moment of the click. It creates only one binding which is also better for global performance.

Jquery function doesn't work after Ajax call

I've got this function:
$(document).ready(function() {
$('.post_button, .btn_favorite').click(function() {
//Fade in the Popup
$('.login_modal_message').fadeIn(500);
// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);
return false;
});
My page loads content with favourite buttons, but after Ajax call and generated additional new content the function doesn't work when you click new content's buttons. What could be not right?
That is because you are using dynamic content.
You need to change your click call to a delegated method like on
$('.post_button, .btn_favorite').on('click', function() {
or
$("body").on( "click", ".post_button, .btn_favorite", function( event ) {
Instead of this:
$('.post_button, .btn_favorite').click(function() {
do this:
$(document).on('click','.post_button, .btn_favorite', function() {
on will work with present elements and future ones that match the selector.
Cheers
class-of-element is the applied class of element. which is selector here.
$(document).on("click", ".class-of-element", function (){
alert("Success");
});
If you know the container for .post_button, .btn_favorite then use
$('#container_id').on('click', '.post_button, .btn_favorite', function () { });
so if '.post_button, .btn_favorite' are not found then it will bubble up to container_id
else if you don't know the container then delegate it to document
$(document).on('click', '.post_button, .btn_favorite', function () { });
Reference
I am not sure if I am getting your question right but you may want to try..
$.ajax({
url: "test.html"
}).done(function() {
$('.post_button, .btn_favorite').click(function() {
//Fade in the Popup
$('.login_modal_message').fadeIn(500);
// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);
return false;
});
Just try to paste your code inside done function.
Hope it helps :)
EDIT:
I also notice you are missing }); on your question.
The following worked for me
$(document).ready(function(){
$(document).bind('contextmenu', function(e) {
if( e.button == 2 && jQuery(e.target).is('img')) {
alert('These photos are copyrighted by the owner. \nAll rights reserved. \nUnauthorized use prohibited.');
return false;
}
});
});
You need to bind the jQuery click event once your ajax content is replaced old content
in AJAX success block you need to add code like here new response html content one a tag like
Click Me
So you can bind the new click event after change the content with following code
$("#new-tag").click(function(){
alert("hi");
return false;
});

How to check if a certain html fragment is already loaded?

Have the following code:
$("#blogs").mouseover(
function () {
$(this).addClass("hover");
$("#home").removeClass("hover");
$("#homepages").removeClass("hover");
$("#apps").removeClass("hover");
$("#facebook").removeClass("hover");
$("#kontakt").removeClass("hover");
$("#content").hide().load("blogs.html", function(){
$("#content").show("slide");
});
});
Works all fine, but now I would like the load() / show() function only be called if #content does not already contain blogs.html.
In other words: I would like to check if blogs.html is already loaded and if yes, simply do nothing and only if not there yet I would load and show it.
Have tried some things with hasClass() and some if-formulas but struggle to get this check.
Tried stuff like this:
$("#content section").hasClass("check_blog").hide().load("blogs.html", function(){
$("#content").show("slide");
Basically I just need to know how I can check if blogs.html is already the contents of #content.
Thanks a lot for any help. Regards, Andi
Add an ID to some element in blogs.html, say blogsloaded, then you can check for it with:
if (!$("#blogsloaded").length)
$("#content").hide().load("blogs.html" ...
Another method would be to store in a variable if you already loaded it:
if (!this.blogsloaded)
{
this.blogsloaded=true;
$("#content").hide().load("blogs.html" ...
}
I would split up your mouseover events into two namespaced events. One which will only run once.
// This event will only run once
$("#blogs").on("mouseover.runonce", function () {
$("#content").load("blogs.html");
});
// because this event will unbind the previous one
$("#blogs").on("mouseover.alwaysrun", function () {
$(this).off("mouseover.runonce");
$(this).addClass("hover");
$("#home").removeClass("hover");
$("#homepages").removeClass("hover");
$("#apps").removeClass("hover");
$("#facebook").removeClass("hover");
$("#kontakt").removeClass("hover");
$("#content").hide();
});​
Update a data attribute on #content that contains the url or id of the currently loaded content. Also, you should handle the case where the user hovers over a different section before the previous is done loading.
var request; // use this same var for all, don't re-declare it
$("#blogs").mouseover(function () {
// exit event if the blog is the current content in #content
if ( $("#content").data("current") == "blog") return;
$("#content").data("current","blog");
$(this).addClass("hover");
$("#home").removeClass("hover");
$("#homepages").removeClass("hover");
$("#apps").removeClass("hover");
$("#facebook").removeClass("hover");
$("#kontakt").removeClass("hover");
// if a previous request is still pending, abort it
if ($.isFunction(request.abort) && request.state() == "pending") request.abort();
// request content
request = $.get("blogs.html");
$("#content").hide();
// when content is done loading, update #content element
request.done(function(result){
$("#content").html(result);
});
});
I strongly suggest against using hover for loading content with ajax.
Also, in it's current form, this code is not very re-usable, you'll have to have one for each link. I suggest instead using classes and having only one event binding handling all of the links.
You can do it like this using .has() to detect descendants of content
$("#blogs").mouseover(
function () {
$(this).addClass("hover");
$("#home,#homepages,#apps,#facebook,#kontakt").removeClass("hover");
var $c = $("#content");
if($c.has('.check_blog')){ // if content contains an element with that class
$("#content").hide().load("blogs.html", function(){
$("#content").show("slide");
}
});
});
You could do something like this:
$("#blogs").mouseover(
function () {
$(this).addClass("hover");
$("#home").removeClass("hover");
$("#homepages").removeClass("hover");
$("#apps").removeClass("hover");
$("#facebook").removeClass("hover");
$("#kontakt").removeClass("hover");
if($('#content').html() == '') {
$("#content").hide().load("blogs.html", function(){
$("#content").show("slide");
});
}
});

Function becomes undefined after first trigger

I have a block of code like so:
function doSomething() {
someVar.on("event_name", function() {
$('#elementId').click(function(e) {
doSomething();
});
});
}
// and on document ready
$(function () {
$('#anotherElemId').click(function () {
doSomething();
});
});
The problem that I'm encountering is that when I call doSomething() from anotherElemId click event(that is binded on document ready) it works as expected, but calling it recursively from elementId click doesn't work.
Any ideas? Thinking is something trivial that I'm missing.
Is someVar an actual jQuery reference to a dom element? (e.g. $('#someitem'))
The second problem is you cant put a .click event inside a function that you would like to instantiate later on. If you are trying to only allow #elementId to have a click event AFTER some previous event, try testing if a tester variable is true:
var activated = false;
$(function () {
$('#anotherElemId').click(function () {
activated = true;
});
$('#secondElemId').on("event_name", function() {
if (activated) {
// code that happens only after #anotherElemId was clicked.
}
});
});

Categories

Resources