Ajax inserted content not accessible in DOM - javascript

I am working on a pure jquery/js site, mostly to practice some jquery. I am using a load statement to load a menu from a file of common html, like so:
$('#categoryListing').load('../common.html #categoryLinksUL');
which loads:
<ul id="categoryLinksUL">
<li>Anklets</li>
<li>Bracelets</li>
</ul>
The problem is where I am using it now I need to alter the href of the above links, but they are not part of the dom. In previous instances I was able to use .live(click... But not here. Is there a way I can accomplish this?
Specifically I need to load the links and change the href from #anklets to ?category=anklets

What about the following?
$('#categoryListing').load('../common.html #categoryLinksUL', function() {
$('li a[href^="#"']').each(function () {
this.href = '?category=' + this.href.substr(1);
});
});
In my example, after the load is completed, the anonymous function is called. It takes every anchor with a hash HREF and replaces it with an HREF based on your description.

Thank you Dimitry, you solution basically worked. I finally used:
$('#categoryListing').load('../common.html #categoryLinksUL', function() {
$('#categoryListing li a').each(function () {
var hashPos=this.href.indexOf("#");
var tCategory = this.href.substr(hashPos+1,this.href.length );
});
});
So why did jQuery recognize categoryListing there? I tried moving the each function outside of the load function and categoryListing did not contain any links. Is it because maybe the load was not completed when it tried to get categoryListing links? Seems like that is possible.
Thanks,
Todd

Related

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 each doesn't work with certain classes, or classes in general?

I'm using Phonegap to build a small (test only) Macrumors application, and remote hosts actually work (there is no same host browser restrictions). I am using the jQuery Load() function to load the contents of the Macrumors homepage http://www.macrumors.com/ into a bin, hidden div, then the each function to loop through all the article classes to show the title in a box with a link to the page.
The problem is, after the Macrumors HTML content is loaded, the each function doesn't work with the article class. Also, in the load function (which allows you to specify certain selectors, id's and classes included, to only load in those sections of the page) the class doesn't work; none of the classes do, in both the load function and each function. And many Id's don't work in the each function either.
Can anybody explain this to a noob like me?
Here is the code:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content');
$('.article').each(function(){
var title = $('a').html();
$('#content').append('<b>'+title+'</b>')
});
}
And the HTML stuff
<body onload="onBodyLoad()">
<div id="bin">
</div>
<div id="content">
</div>
</body>
I sincerely apologize if there's some very simple mistake here that I'm missing; I'm a major JS newbie.
.load() is asychronous. It hasn't completed yet when you're executing .each(). You need to put your .each() and any other code that wants to operate on the results of the .load() in the success handler for .load().
You would do that like this:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content', function() {
$('.article').each(function(){
var title = $('a').html();
$('#content').append('<b>'+title+'</b>')
});
});
}
I'm also guessing that your .each() function isn't working quite right. If you want to get the link out of each .article object, you would need your code to be like this so that you're only finding the <a> tag in each .article object, not all <a> tags in the whole document:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content', function() {
$('.article').each(function(){
var title = $(this).find('a').html();
$('#content').append('<b>'+title+'</b>')
});
});
}

jQuery load with variable instead of element id

i've got a slight jQuery problem.
What i want is to load a particular area of an external html doc into a div,
instead it loads the whole document, not the specified area.
This is the trigger:
$('a').click(function(){ // my link to trigger the load
var pid = $(this).attr('href'); //the pid is the links href
getproject(pid); //trigger the load function, pass variable
});
This is the triggered function:
function getproject(pid) {
$('#container').load('data.html', pid);
}
So when i click my link, it should load the element with the id (#) specified by the link into my container, but it loads the whole data... i cant seem to find a solution to this.
The Link looks like this (cant use exact markup here):
a href="#elementtoload"
The data document looks like this:
div id="elementtoload"
div id="..."
and loads of more elements with content, which should be loaded by id from the links href.
Looking at the documentation for $ load, you should be able to do this:
function getproject(pid) {
$('#container').load('data.html #' + pid);
}
http://api.jquery.com/load/
Second section, Loading Page Fragments. For us to say exactly how this is relevant, you'd need to provide an example of the triggering link, and ideally the document you're loading.
Not sure what your actual intent is but it seems to me that you are going to alot of trouble to get the pid but then not using it in your load routine. I'm guessing the code should look more like this:
function getproject(pid) {
$(pid).hide().load('data.html');
}
String concatenation:
.load('data.html ' + pid);
Regarding your update:
<div id="#elementtoload"> should be <div id="elementtoload">
I was trying something similar and after some hours (...) michael came finally with something that works :) this did the trick for me, the # should be in the url string, like this:
$('#div1').load('data.html #' + x);

Categories