AJAX based page needs repetitive javascript actions - javascript

I'm working on an application that uses JQuery layouts and loads only website parts (like Gmail). Every time I load a "panel" using JQuery I have to substitute some links to make it work with panels (i.e., to load this link content in a panel, not in the full page). Is something like this:
function changeMainPane(href) {
$("#screen").load(href);
$("#screen a.ajax-page").click(function () {return
changeMainPane($(this).attr("href"))
});
}
This is a very simplified changeMainPane function, mine has tens of $("#screen ...").click() calls to integrate the new piece of HTML into the page.
The question is: there is any better way to do this? Something like:
$("#screen").ready(function() {
// All my html setups
}
Or something like "always a user clicks on a link, check if has ajax-page class and the call this function" without having to initialize each link independently.

You can have a look at the delegate method. The delegate method can be registered for the common parent element of all the links on which you wants to reload the main panel. It can be the document object or a lower level element like "body" or another div like "div.mylinks".
$(document).delegate("a.ajax-page", "click", function(){
changeMainPane($(this).attr("href"))
})

Maybe jQuery live() is what you're looking for. You use it like this:
$("#screen a.ajax-page").live('click', function () { whatever; });
Then you don't need to reinitizalize after ajax activity.

Related

Show all hidden elements when a page loads with override?

I have a page that forces some JS to load on a page that I need to override. I can load a separate JS file to do this. I want to have the page do the .show for any of the .below-the-folds on the page. I guess the best way to say it is, I want all the "more" things on the page to be expanded when the page loads, rather than making a person click more to see what's below the fold on all these.
This is the JS I need to override, I can't change it since it's loaded by the app automatically. There can be more than one of the lists hidden, I'm not sure how much harder that makes things.
function MoreFacets($more_facets_div) {
this.$more_facets_div = $more_facets_div;
this.bind_events();
};
MoreFacets.prototype.bind_events = function() {
var self = this;
self.$more_facets_div.find('.more').on('click', function (e) {
$(this).siblings('.below-the-fold').show();
$(this).hide();
});
self.$more_facets_div.find('.less').on('click', function (e) {
$(this).parent().hide();
$(this).parent().parent().find('.more').show();
});
};
$(function() {
$('.more-facets').each(function() {
new MoreFacets($(this));
});
});
It's loaded on the page and the HTML looks like this:
<h3>Additional filters: </h3>
<dl id="facets">
<dt>Collecting Area</dt>
<dd> Here's Something in the list</dd>
<dd> Here's the last in the list</dd>
<div class="more-facets">
<span class="more btn">∨ more</span>
<div class="below-the-fold">
<dd>Something That's hidden is here</dd>
<dd>Something more in this hidden list</dd>
So when the ∨ more is clicked is when the others below-the-fold appear, and that's what I want to load when the page loads. There's usually a few different lists like this on the page.
So I'm thinking what I need to do is something like run the ('.below-the-fold').show() for all the lists when the page loads?
Update A note to clarify: when the page loads now they're all hidden. I'd like them to all show when the page is loaded so no one has to click anything to have everything showing.
Another note based on another question below... It's loaded in a separate file, and I can load my file before that one. I do know that I can override other JS on the page, so I assume I can override this as well.
Based on your last edit, it sounds like you're already onto the fastest solution to your problem.
Please note, this will only work if the script is not loaded asynchronously, but if you have control of the order the scripts are loaded in, you can insert your script between the problem script and jQuery.
Your script can be something as easy as redefining the function it's using to something like this:
MoreFacets.prototype.bind_events = function() {
var self = this;
//Autostart in our open state without completely disabling the functionality
self.$more_facets_div.find('.below-the-fold').show();
self.$more_facets_div.find('.more').hide();
self.$more_facets_div.find('.more').on('click', function (e) {
$(this).siblings('.below-the-fold').show();
$(this).hide();
});
self.$more_facets_div.find('.less').on('click', function (e) {
$(this).parent().hide();
$(this).parent().parent().find('.more').show();
});
};
Now, that won't work if you don't have control over the script loading, but you might have hope even in that case, because document ready functions in jQuery are invoked in the order they're registered, so if you can't really control where your script is you might play with an alternative
$(function() {
$('.more-facets').each(function() {
$(this).find('.below-the-fold').show();
$(this).find('.more').hide();
});
});
The first will be cleaner, but the second is a fallback for more restrictive situations, and both should achieve your desired effect without completely removing the functionality, just changing the default state on load.

Rerun Jquery function onclick

I have a simple jquery script that changes the url path of the images. The only problem is the doesn't apply after I click the load more button. So I'm trying to do a workaround where it calls the script again after clicking the button.
<script type='text/javascript'>
$(document).ready(function ReplaceImage() {
$(".galleryItem img").each(function() {
$(this).attr("src", function(a, b) {
return b.replace("s72-c", "s300")
})
})
});
</script>
HTML
Load More
While Keith's answer will get you what you are looking for, I really can't recommend that approach. You are much better off with something like this.
<script type="text/javascript">
$(function() {
var replaceImage = function() {
$('.galleryItem img').each(function() {
$(this).attr('src', function(index, value) {
return value.replace('s72-c', 's300');
});
});
};
replaceImage();
$('.js-replace-image').on('click', replaceImage);
});
</script>
Using this html
<button class="js-replace-image">Load More</button>
By taking this approach, you do not expose any global variables onto the window object, which can be a point of issue if you work with other libraries (or developers) that don't manage their globals well.
Also, by moving to a class name and binding an event handler to the DOM node via JavaScript, you future proof yourself much more. Also allows yourself to easily add this functionality to more buttons very easily but just adding a class to it.
I updated the anchor tag to a button because of the semantics of what you need to do - it doesn't link out anywhere, it's just dynamic functionality on the page. This is what buttons are best served for.
I'd also recommend putting this in the footer of your site, because then, depending on your situation, you will already have the images updated properly without having to click the button. The only need for the button would be if you are dynamically inserting more images on the page after load, or if this script was in the head of your document (meaning jQuery couldn't know about the images yet).
I hope this helps, reach out if you have questions.

Ajax loaded part of a page - how do I make links in the loaded content work?

I load a part of my basketpage inside an accordion div in my header. This works great and shows my basket in a nice dropdown.
The last problem I need to solve with this is to get the buttons in the loaded content to work. Is it possible to write an callback that make these works? Im not sure even what to google for this one..
This is how the buttons is setup in the loaded content:
checkout
Script Im using to load the content:
$('.dcjqg-accordion ul.sub-menu').load('/m4n?seid=etailer-basket div#centerbox.itembox.centerbox');
use the callback function of .load().
$('.dcjqg-accordion ul.sub-menu').load('/m4n?seid=etailer-basket div#centerbox.itembox.centerbox', function() {
$("#_ec_oie2").on("click", function() {
if (UI.pb_boolean(this, 'click')) { }
return false;
});
});
checkout
You need to use a child selector for the event. You can attach an event to the .sub-menu element that will fire on the content loaded in through the ajax. Something like the following could work:
$(".dcjqg-accordion ul.sub-menu").on("click", ".action.actionbasket.checkout", function() {
if( UI.pb_boolean(this, 'click') ) {}
return false;
});
Notice the second parameter to the on method. It is a selector that will be used to look at the target of the click event. I used .action.actionbasket.checkout since that is what is on your a tag.
This code may not work exactly, but this should help get you in the right direction.
Here is the link to the jQuery documentation for the on method: https://api.jquery.com/on/

Call function anytime a link is moused over on an arbitrary page?

I apologize for the possibly naive nature of this question but I am not a web developer by day.
Is it possible to write a script such that, for any arbitrary web page, a function that I have written will be called if a URL is moused over? I was initially thinking that I could use document.links to assemble an array of all of the hrefs in a document and add an onmouseover event attribute to each of them but, unless I'm mistaken, that would overwrite any existing onmouseover attributes already present in the page. Not ideal.
I'm not sure if by arbitrary web page you mean any pages on any domains or any pages of your own domain, but for the latter you could put something like the following in your pages:
$(function () {
$(document).on('mouseenter', 'a', function () {
console.log(this, 'hovered');
});
});
If you mean any page your browse to on the net, then you will have to write a browser extension for the browser your are using. For Chrome have a look at this.
You could try getting everything with the a tag and inject an onmouseover.
window.onload = function(){
for(m=0;m<document.getElementsByTagName('a');m++){
if(document.getElementsByTagName('a')[m].className == 'someclass'){
document.getElementsByTagName('a')[m].onmouseover = function(){
Your Code
}
}
}
}

JQuery Mobile Custom Flipbox set initialization value

I have a custom flipbox which is described in the accepted answer here: JQuery Mobile Custom Flipbox get selected value.
I'm struggling to set the initial value after the page is rendered my 'change-page' function is something like this:
changePage:function (page) {
page.$el.attr('data-role', 'page');
page.render();
$('body').append(page.$el).trigger('create');
$.mobile.changePage(page.$el, {changeHash:false});
}
As I use Backbone.js to manage the views and then I delegate the navigation to jQM.
I basically need to set the initial value of this input text field ( maybe there's a workaround)
Ok I figured this out myself and I'm willing to share the solution:
first of all the change page function is slightly different:
changePage:function (page) {
page.$el.attr('data-role', 'page');
//get rid of everything in the old page.
page.remove();
//render the page again
page.render();
$('body').append(page.$el).trigger('create');
$.mobile.changePage(page.$el, {changeHash:false});
}
the remove call is necessary to get rid of every event listener you had in the old rendered HTML.
In every page that needs init parameters you can specify in the render function this:
render: function(){
....
this.$el.on('pageshow',this.initFields);
....
}
initFields: function(){
// put your jQuery code here (e.g. this.$el.find('foo').val('initValue');
}
please note that this solution as of the jQM documentation is valid up to the 1.5.0 version of jQM, after that the pageshow event will not be triggered anymore.

Categories