Targetting elements loaded with jquery load() - javascript

I am doing a website where all internal links make the current page fade out and the new contents fade in. I do that with jquery load(). The loading and fading part works fine like this:
var $mainContent = $("#ajaxcontainer"),
$internalLinks = $(".internal"),
URL = '',
$ajaxSpinner = $("#loader"),
$el;
$internalLinks.each(function() {
$(this).attr("href", "#" + this.pathname);
}).on('click', function() {
$el = $(this);
URL = $el.attr("href").substring(1);
URL = URL + " #container";
$mainContent.fadeOut(500, function() {
$ajaxSpinner.fadeIn();
$mainContent.load(URL, function() {
$ajaxSpinner.fadeOut( function() {
$mainContent.fadeIn(1000);
});
});
});
});
As you can see, I am targetting all internal links by a class I've given them (.internal). My problem is that once content gets loaded with ajax, I am not able to target this new content with my jquery, and so the $internalLinks.each() and so on gets broken, meaning that the site just reverts back to the default link behavior.
Another thing which is related to this, is that I want to be able to target this newly loaded content with the jquery.masonry plugin. That also isn't possible the way I'm doing things now.
Thank you very much.

When you update the page, the old .internal links are removed, so the event handler attached to them won't work. Change your code to use event delegation:
$('.internal').each(function() {
$(this).attr("href", "#" + this.pathname);
});
$(document).on('click', '.internal', function() {
$el = $(this);
URL = $el.attr("href").substring(1);
URL = URL + " #container";
$mainContent.fadeOut(500, function() {
$ajaxSpinner.fadeIn();
$mainContent.load(URL, function() {
$ajaxSpinner.fadeOut( function() {
$mainContent.fadeIn(1000);
});
$('.internal').each(function() {
$(this).attr("href", "#" + this.pathname);
});
});
});
});
As you see, I refresh the attribute href of each link after a refresh, too.
** EDITED ** I was missing changing the href attribute the first time. Now it should work!

Related

jquery - colorbox - adding a function to the popup

I have a "quick view" feature that captures a dynamic URL also known as "qvURL" and creates a colorbox with it via:
<script type="text/javascript">
$(function(){
$(".quickview_btn").click(function(e){
e.preventDefault();
var qvURL = $(this).attr("href");
$.colorbox({"href": qvURL})
});
$.colorbox.resize();
});
</script>
Now. I need to make some changes in the child window - but it seems the AJAX or whatever is wiping out the entire DOM and anything I load from the parent window doesn't reflect.
For instance - let's say I just want to add a div that says qwerty!
[I'm actually wanting to create an mbox around a Call To Action]
Any insight would be greatly appreciated!
Please note - the URLs it's loading is content that I can not manipulate - so it has to be done in the parent window.
Thanks!
Please see below for my full snippet:
<script>
$( document ).ready(function() {
$('.quickview_btn').click(function(){
//Quickview tracking
$('.quickview').attr('id', 'quickviewClicked-area');
mboxDefine('quickviewClicked-area','quickviewClicked','clicked=Y');
$( 'div.quickview' ).bind( 'click', function() {
console.log('clicked!');
product = $(this).children().attr('href');
console.log(product)
mboxUpdate('quickviewClicked', "link="+product);
});
//thumbnail add to cart tracking
$('div.add-to-cart').attr('id', 'ThumbnailAddToCart-area');
mboxDefine('ThumbnailAddToCart-area','ThumbnailAddToCartClicked','clicked=Y');
$( 'div.qlBtns' ).bind( 'click', function() {
;
mboxUpdate('ThumbnailAddToCartClicked', "clicked=Y");
console.log('mbox updated!')
});
});
});
/*
$(document).ready(function(){
$(qvURL).$colorbox({
iframe : true,
frastIframe: false,
onComplete: function(){
$('.name').html('yeah you got it');
}
});
});
*/
</script>
< script >
$(document).ready(function() {
$('.quickview_btn').click(function() {
//Quickview tracking
$('.quickview').attr('id', 'quickviewClicked-area');
mboxDefine('quickviewClicked-area', 'quickviewClicked', 'clicked=Y');
$('div.quickview').bind('click', function() {
console.log('clicked!');
product = $(this).children().attr('href');
console.log(product)
mboxUpdate('quickviewClicked', "link=" + product);
});
//thumbnail add to cart tracking
$('div.add-to-cart').attr('id', 'ThumbnailAddToCart-area');
mboxDefine('ThumbnailAddToCart-area', 'ThumbnailAddToCartClicked', 'clicked=Y');
$('div.qlBtns').bind('click', function() {;
mboxUpdate('ThumbnailAddToCartClicked', "clicked=Y");
console.log('mbox updated!')
});
});
});
/*
$(document).ready(function(){
$(qvURL).$colorbox({
iframe : true,
frastIframe: false,
onComplete: function(){
$('.name').html('yeah you got it');
}
});
});
*/
< /script>
I see this line in your code:
$.colorbox({"href": qvURL})
and my first question is whether or not that selector is enough. Mind you I am more a middle-ware than a client-side guru, but from my knowledge of jQuery, that selector won't do anything because jQuery can't tell what you mean. See how you used the quotes in the assignment of the click function?
$(".quickview_btn").click(function(e){
e.preventDefault();
if you used $("#colorbox") to get the object (if that is its id) or $(".colorbox" if is is a a class you are targeting.
(I am not an expert, as I said, but those who are agree:
$(".someClass") selects all elements with class name someClass
$("#testButton") selects the element with the id value of testButton
-- Courtesy of the DZone jQuery Ref Card at https://dzone.com/refcardz/jquery-selectors
So it may be that everything else is fine, you just aren't passing your code anything to hook into the colorbox object.

Bind bxslider after ajax call in WP

Please help me with binding bxSlider on Ajax response, tried on. , tries function after but no help (think problem with lack of JS syntax knowledge).
Here's JS:
$('.catalog-menu-links a').click(function(event) {
event.preventDefault();
// Set class to newly selected language button
$('.catalog-menu-links li.current-menu-item').removeClass('current-menu-item');
$(this).parent().addClass('current-menu-item');
// Get new language data URL
var href = $(this).attr("href");
$.get(href, function(data) {
var ajaxCatalogSliderContent = $(data).find('.catalog-slider').html();
$('.catalog-slider').fadeOut('slow', function(){
$('.catalog-slider').html(ajaxCatalogSliderContent);
}).fadeIn();
//alert($('.catalog-slider').html());
$('body .bxslider-catalog').bxSlider({pager: true,controls: true,mode: 'fade'});
});
});
I tried this:
function startCatalogSlider() {
$('.bxslider-catalog').bxSlider({pager: true,controls: true,mode: 'fade'});}
startCatalogSlider();
$('.catalog-menu-links a').click(function(event) {
event.preventDefault();
// Set class to newly selected language button
$('.catalog-menu-links li.current-menu-item').removeClass('current-menu-item');
$(this).parent().addClass('current-menu-item');
// Get new language data URL
var href = $(this).attr("href");
$.get(href, function(data) {
var ajaxCatalogSliderContent = $(data).find('.catalog-slider').html();
$('.catalog-slider').fadeOut('slow', function(){
$('.catalog-slider').html(ajaxCatalogSliderContent);
}).fadeIn();
//alert($('.catalog-slider').html());
startCatalogSlider();
});
});
But with no successful result

Best practice for handling jquery ajax response

I've done a lot of reading over the last few years trying to become proficient with JavaScript and it's frameworks. It seems that most texts either teach the rudiments of ajax, loading something into an empty element, or they assume you know what your doing and glance over the data handling portion. I've developed my own methods over time, but having nothing to compare them too. I don't know how efficient they are. When building a ajax based site I typically use jquery and history.js and my code is as follows.
function updateContent(state){
var theUrl = state.data.urlPath; //the url of what needs ajaed in
$('#container #content').fadeOut(500, function(){ //fade out old content
var newContent = {};
newContent.load(theUrl + ' #content', function(){ //load new content into object
newContent.hide(); //hide it so it can be faded in
$('#container').html(newContent); //replace content in container
newContent.fadeIn(500); //fadein content
});
});
}
var History = window.History;
if (History.enabled) {
var State = History.getState();
History.pushState({urlPath: window.location.href}, $("title").text(), State.urlPath);
} else {
return false;
}
History.Adapter.bind(window, 'statechange', function() {
updateContent(History.getState());
});
$(document).on('click', 'a', function(evt){
var testSite = /http:\/\/www.example.com(\/)?/ //regex to test if is local link
var theUrl = $(this).attr('href'); //the url of the clicked link
if(testSite.test(theUrl)){
evt.preventDefault();
History.pushState({urlPath: theUrl}, title, theUrl);
}
});
This is the basics of my code. I feel it is inefficient particularly when the back button is used. When going back the content has to be reloaded. Is there a more efficient way to do this?

Redirect links on a webpage to a javascript function

I am trying to redirect links on a web page and in this simple example, it just goes through a simple check for a cookie to be set.
Not sure if that's the right way to take care of this situation in the first place, and if I am going to run into problem when there are several links with the "download_link" class, but even right now, with only one of such link, the destination is set to undefined, it looks like the $(this) in the call to redirector is actually pointing the the whole HTML document instead of just the element I am trying to change...
function redirect_link(e, destination) {
if ($.cookie("contact_set") == "true") {
window.location.href = destination;
} else {
alert("cookie not set");
}
}
function redirector(destination) {
alert("creating redirector to "+destination);
return function(e) {redirect_link(e, destination)};
}
$(document).ready(function() {
$('.download_link').click(redirector($(this).attr("href")));
$('.download_link').attr("href", "#");
});
You're accessing $(this) from the scope of document's ready callback, so $this points to a HTMLDocument object!
$(document).ready(function() {
var $downloadLnk = $('.download_link');
$downloadLnk.click(redirector($downloadLnk.attr("href")));
$downloadLnk.attr("href", "#");
});
As you requested it in your comment:
$(document).ready(function() {
$('.download_link').each(function() {
var $lnk = $(this);
$lnk.click(redirector($lnk.attr("href")));
$lnk.attr("href", "#");
});
});
$(function() { // <-- Short for $(document).ready(function() {
$('.download_link').each(function() {
var $this = $(this);
$this.click(redirector($this.attr("href"));
$this.attr("href", "#");
});
});
You can always use the target :
$(document).ready(function() {
$('.download_link').on('click', redirector); //bind to function
$('.download_link').attr("href", "#");
});​
function redirector(event) {
alert("creating redirector to "+event.target.href); //event.target
return function(e) {redirect_link(e, destination)};
}
But by the time your link is clicked the href will be # no matter what you use, as you set it to that value on the next line after the click handler ?

jQuery: Simple menu

I'm trying to learn jQuery by implementing a simple menu. I've got <div> elements that act as buttons and have links in them. I'm trying to add onclick events to the divs that navigate the browser to the link's address in the div. This is basically my pseudo-code. What would the real code be? How can I improve this? Any feedback appreciated!
// Iterate over each menu button
$('.masterHeaderMenuButton').each(function () {
// Get the link in each button and set the button's onclick to
// redirect to the link's address
var url = $('a', this).attr('href');
this.click(function () {
window.location.href = url;
});
// If the user is on the page for the current button, hilight it
if (window.location.href === url) {
$('a', this).addClass("masterHeaderMenuButtonSelected");
}
});
Try this untested example:
$('.masterHeaderMenuButton a').each(function () {
// Get the link in each button and set the button's onclick to
// redirect to the link's address
var _this = this; // save this ref for click handler.
$( this ).parent().click(function () {
window.location.href = $(_this).attr('href');
});
// If the user is on the page for the current button, highlight it
if (window.location.href === url) {
$(this).addClass("masterHeaderMenuButtonSelected");
}
});
I don't actually use jQuery for such a simplistic task, especially if it involves page redirection. So unless you're looking to do some AJAX-style page loading, stick with standard HTML.
For that task, I use this sweet combo:
$('#nav_links li').live('click', function() {
var ajax_link = $(this).attr('rel');
loadLink(ajax_link);
});
function loadLink(link){
$('#content_window').css('position','relative');
$('#content_window').animate({
'left': '20px',
'opacity': '0'
}, 500, "swing", function() {
$.ajax({
url: '../sections/' + link,
dataType: 'html',
success: function(html) {
$('#content_window').html(html);
}
});
});
}
Awesome, right?
Here's the HTML:
<ul id="nav_links">
<li rel="setting-up.html"><span class="green">|</span>setting up<br></li>
<li rel="features.html"><span class="purple">|</span>features<br></li>
<li rel="more-uses.html"><span class="blue">|</span>more uses<br></li>
<li rel="troubleshooting.html"><span class="yellow">|</span>troubleshooting</li>
</ul>
Have a fun.

Categories