Bind bxslider after ajax call in WP - javascript

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

Related

Targetting elements loaded with jquery load()

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!

jQuery- Inserting GET data into div only works after second trigger

I am trying to use jQuery to fetch data and place it into a div after I hover over a link. It is working, but only on the second hover. The first hover instance does not do anything. Why?
jQuery(document).ready(function($){
$(".tiptrigger").hover(function() {
var s_href = $(this).attr('href');
var s_title = $(this).attr('title');
$(".tiptitle").empty().append(s_title); // Only working after second instance
var get_url = "/root/data.php"+s_href;
$.get( get_url, function( data ) {
var tip_content = data;
$("#tipcontent").empty().append(tip_content); // Only working after second instance
});
});
And the HTML:
<a class="tiptrigger" title="My Title" href="?s=something">Hover over me</a>
<div class="tipbox"><p class="tiptitle"></p><p id="tipcontent"></p></div>
And lastly, the PHP page that the GET request is being sent to:
<?php
if ($_GET['s'] == "something") {
echo "This should appear in the paragraph.";
}
?>
What am I doing wrong here?
Provide an empty stub function for the handlerOut() second handler of .hover(), you are just providing one handler, which is executed both when going over and out of the link, so do it like this:
$(".tiptrigger").hover(function() {
var s_href = $(this).attr('href');
var s_title = $(this).attr('title');
$(".tiptitle").empty().append(s_title); // Only working after second instance
var get_url = "/root/data.php"+s_href;
$.get( get_url, function( data ) {
var tip_content = data;
$("#tipcontent").empty().append(tip_content); // Only working after second instance
}
, function() {}); //PROVIDE EMPTY HANDLER FOR MOUSEOUT

History api statechange function script duplicates function calls each time change occurs

I'm using the jquery history plugin in a simple demo that loads in a section of a specific page each time you click a nav item, what i've found though is that each time I click a new link the History.Adapter.bind(window, 'statechange', function() code is duplicated. Is it possible to unbind this every time the code has finished inside this function or can anyone advise where I may be going wrong with this?
My test page http://kylehouston.com/_testing/history/page1.html
JS
navLink.on('click', function(e) {
e.preventDefault();
var el = $(this);
//get the href and remove begining /
url = el.attr('href')
.slice(1);
//do a check to see if this link is already active
if (el.hasClass('is-active')) {
return false;
}
navLink.removeClass('is-active');
el.addClass('is-active');
History.pushState(null, null, url);
// Bind to StateChange Event
History.Adapter.bind(window, 'statechange', function() {
var State = History.getState();
mainContent.fadeOut(function() {
$(this)
.empty();
console.log('this ran');
preloader.fadeIn();
loadContent(mainContent, location.pathname);
});
History.Adapter.unbind();
});
//empty mainContent then empty it
mainContent.fadeOut(function() {
$(this)
.empty();
//display preloader
preloader.fadeIn();
//check if content already exists in pages{} if not then make call then save to pages{} or retrieve from pages{} if already exists
loadContent(mainContent, url);
});
});
Have you tried to move
// Bind to StateChange Event
History.Adapter.bind(window, 'statechange', function() {
var State = History.getState();
mainContent.fadeOut(function() {
$(this).empty();
console.log('this ran');
preloader.fadeIn();
loadContent(mainContent, location.pathname);
});
});
before
navLink.on('click', function(e){

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 ?

Why does my jQuery event handler fail when attached to multiple elements?

I am using jquery to add mulitple new "addTask" form elements to a "ul" on the page every time a link is clicked.
$('span a').click(function(e){
e.preventDefault();
$('<li>\
<ul>\
<li class="sTitle"><input type="text" class="taskName"></li>\
<li><input type="button" value="saveTask" class="saveTask button"></li>\
</ul>\
</l1>')
.appendTo('#toDoList');
saveTask();
});
These new nested ul elements all have an button with the same class "saveTask". I then have a function that allows you to save a task by clicking on an button with the class "saveTask".
// Save New Task Item
function saveTask() {
$('.saveTask').click(function() {
$this = $(this);
var thisParent = $this.parent().parent()
// Get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save',
data, function(data) {
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
}
This essentially allows the user to enter some text into a form input, hit save, and then the task gets saved into the database using ajax, and displayed on the page using jQuery.
This works fine when there is only one element on the page with the class "saveTask", but if I have more than 1 form element with the class "saveTask" it stops functioning correctly, as the variable "var task" shows as "undefined" rather than the actual value of the form input.
Don't rely on the .parent() method. Use .closest('form') instead. So the following line:
var thisParent = $this.parent().parent()
should look something like this instead:
var thisParent = $this.closest('form');
EDIT:
Based on the updated information you provided, it looks like when you're trying to register the click event handler it's failing out for some reason. Try this javascript instead as it will make use of the live event so that all the newly added items on the page will automatically have the click event autowired to them.:
$(function(){
$('span a').click(function(e){
e.preventDefault();
$('<li>\
<ul>\
<li class="sTitle"><input type="text" class="taskName"></li>\
<li><input type="button" value="saveTask" class="saveTask button"></li>\
</ul>\
</l1>')
.appendTo('#toDoList');
});
$('.saveTask').live('click', function() {
$this = $(this);
var thisParent = $this.closest('ul');
// Get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save',
data, function(data) {
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
});
First turn the save task into a function:
(function($){
$.fn.saveTask= function(options){
return this.each(function(){
$this = $(this);
$this.click(function(){
var thisParent = $this.parent().parent()
//get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save', data, function(data){
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
});
});
return false;
})(jQuery)
When the app starts change the saveTask selector to this:
function saveTask(){
$('.saveTask').saveTask();
}
Then on your add function:
function addTask(){
$newTask = $("<div>Some Task stuff</div>");
$newTask.saveTask();
}
This code is written very quickly and untested but essentially create a jQuery extension that handles for data submission then when ever a task is created apply the save task extension to it.
I think you're looking for the live event.
Also, your code is a little awkward, since the click event is only added when the saveTask() function is called. In fact, the saveTask() function, doesn't actually save anything, it just adds the click event to the elements with the .saveTask class.
What is your HTML structure?
It looks like your code can't find the input.taskName element.
Try setting thisParent to something like $this.closest('form'). (Depending on your HTML)
You could try wrapping your click function in an each()
ie
function saveTask(){
$('.saveTask').each (function () {
$this = $(this);
$this.click(function() {
var thisParent = $this.parent().parent()
//get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save', data, function(data){
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
})
}
I find this helps sometimes when you have issues with multiple elements having the same class

Categories