jQuery .load by element ID - javascript

Hi I'm trying to load an element from a webpage via ID.
My code reads the url from the 'href' attribute of the tag and then loads the page. I'm stripping the document anchor.
This script works but won't discard the surround elements and loads the entire page.
<script type="text/javascript">
$(function() {
var a_href = $('#pycom').attr('href').split('#');
$('div#pop-up').load(a_href[0] + '#synopsis');
});
</script>
<body>
<a id="pycom" href="content/documentation/CommandsPython/ls.html#hFlags">ls</a>
</body>
http://help.autodesk.com/cloudhelp/2015/ENU/Maya-Tech-Docs/CommandsPython/ls.html
The above link exists locally on my server (XAMPP) as per the 'html' code above.
Below is the element I would like to extract.
<p id="synopsis">
<code>
xform([objects...],
[absolute=<i>boolean</i>],
[boundingBox=<i>boolean</i>],
.....
.....
</code>
Thanks
Jamie

At first get your page, and then inside the
content find your element with id named 'synopsis' as below:
var a_href = $('#pycom').attr('href').split('#');
$("div#pop-up").load(a_href[0] + " #synopsis" );
It should work, but before that check whether your browser supports mixed content. If your url contains http inside https then browser may not support, In that case you have to disallow the checking in the browser.
Thanks.

OK solved. I was using jQuery 2.4.1 which apparently has a bug that is supposed to be fixed.. but appears to be not?? see here http://bugs.jquery.com/ticket/14773
I am instead using jQuery 1.11.3
below is my final code:
<script type="text/javascript" src="content/scripts/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(function() {
var moveLeft = -10;
var moveDown = 10;
$('a#pycom').hover(function(e) {
var a_href = $(this).attr('href').split('#');
$('#pop-up').load(a_href[0] + ' #synopsis');
$('div#pop-up').show().css('top', e.pageY + moveDown).css('left', ((e.width/100)*1) + moveLeft);
}, function() {
$('div#pop-up').hide();
});
});
</script>
The following method using .get also works exactly the same except gives the benefit of being able to process the returned string in the callback.. in this case the trailing section of the requested selected element... very nice stuff.
$('a#pycom').hover(function(e) {
var a_href = $(this).attr('href').split('#');
$.get(a_href[0], function(response) {
$('#pop-up').html($(response).filter('#synopsis').html().split('<br>')[0]);
});
});
Now owning jQuery like a BOSS!!
Thank you to all those who helped out.
Chur!
J

You should not give any space in the URL. There is a space before ' #synopsis'.
$('div#pop-up').load(a_href[0] + '#synopsis');

Related

Trying to use jQuery to trigger an anchor click after the page loads

So this has been asked a number of times on here, and while I've read all of the threads I can find, this still isn't working for me.
A little background: I'm working on a Wordpress site with a grid plugin, and I'm trying to trigger a filter when the page loads, depending on a url parameter. For the purpose of this thread I've just hardcoded a url parameter (the category variable) as an example because that functionality is working fine.
The anchor tag I'm trying to trigger:
Tarps and Covers
The broken code I'm trying to use to trigger the click event:
<script type="text/javascript">
$(document).ready(function() {
var hash = window.location.hash;
var category = '55';
var anchor = $("[data-category=" + category + "]");
anchor.click();
});
</script>
A console log returning the anchor variable confirms that I'm selecting the correct jQuery object, and I've also tried anchor[0].click() to trigger it with no success. Does anyone see any problems that I'm overlooking?
I tried it :
$(document).ready(function() {
var hash = window.location.hash;
var category = '55';
var anchor = $("[data-category=" + category + "]");
anchor.click();
anchor.on('click',()=>{
alert();
})
});
Everything is working

Get id of element within ckeditor

Unfortunately I have to open a new question for this as I cannot yet add comments to replies (in foreign posts).
In this question (Clicking CKEditor content to show alert) Palec posted a solution to get onclick events within CKEditor that works very well for me but as I hardly know jQuery I would need to know how I can get the id of the element (in this case the id of a div) within CKEditor using the code below.
This is the piece of code that I'm talking about.
CKEDITOR.on('instanceReady', function() {
$('.cke_contents iframe').contents().click(function() {
alert('Clicked!');
});
});
Thanks for your help,
Pascal
You can get the id of an element in native Javascript using
element.id
and in jQuery using
$('element').attr('id')
Working Example:
// Native Javascript
var myDiv = document.getElementsByTagName('div')[0];
var myDivId = myDiv.id;
window.alert('Native javascript has found the id of the <div> is "' + myDivId + '"');
// jQuery
$(document).ready(function(){
alert('jQuery Library has found the id of the <div> is "' + $('div').attr('id') + '"');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my-div"></div>

jQuery load local iframe url with escaped characters for disqus commenting

I'm loading a custom page type that is just comments for a post. This is so I can use Disqus threads for easier usability when multiple loop posts are on a single page.
When loading an iFrame with the following structure I keep getting this syntax error. Are my escape characters wrong?
$(".boxyComments a").click(function (event) {
event.preventDefault();
var post_id = $(this).attr("rel");
$(".commentsIframeBig")
.get(0).contentWindow.location.href =
$("<?php echo get_site_url(); ?>","\/ajax-post-fold\/",post_id);
What's happening is the get retrieves the Wordpress hook to print the site url (in this case it prints http://whateverdomainex.com for the 1st call, 2nd should print /ajax-post-fold/ and the last call should print the post ID so the entire url ends up printing as http://whateverdomanex.com/ajax-post-fold/2825.
Instead my Chrome console gives me the following message:
Uncaught Error: Syntax error, unrecognized expression: /ajax-post-fold/
Update
I've put this variable into place and called it rather than the $("<?php echo get_site_url(); ?>","\/ajax-post-fold\/",post_id); as the get reference:
var postLink = $("<?php echo get_site_url(); ?>"+"\/ajax-post-fold\/"+post_id);
Implemented as such:
$(".boxyComments a").click(function (event) {
event.preventDefault();
var postLink = $("<?php echo get_site_url(); ?>"+"\/ajax-post-fold\/"+post_id);
var post_id = $(this).attr("rel");
$(".commentsIframeBig")
.get(0).contentWindow.location.href = postLink;
Which gives me the following Chrome message:
Uncaught Error: Syntax error, unrecognized expression: http://www.theciv.com/ajax-post-fold/28448
The URL that should be in the src attribute for the iFrame looks like it should be fine and good to go, so why is this syntax error still being output?
UPDATE
var postLink = "<?= site_url('\/ajax-post\/'); ?>"+post_id;
$(this).closest(".boxy").find(".commentsIframeBig")
.css("display","block")
.animate({height: "100%"}, 500)
.get(0).contentWindow.location.href = postLink;
With the proper structure above, the custom page is now loading in the iFrame. However the additional construct of +page_id which includes the rel attribute containing the post's id isn't loading properly.
Moreover when calling the new url as it's original custom page template, then adding the post's id does not load the correct page with post id. Confused yet? Read it again. Took me awhile to write that sentence.
In any case, now my mission to have the post id load when adding the custom page and the post_id as an added string for the iFrame's url to load properly.
update
Here is final working code to load Disqus comments into same page, pseudo multiple times.
Basically this is pushing a post id to the end of a custom page type, resulting in the post's content and attributable elements being loaded into the custom page template.
When stripping that custom page template down to just show the comments for the page, you can create a load/unload reaction whereby you are only calling Disqus once, removing that instance and then loading it again when another Load Comments button is clicked within a subsequently loaded post on the same page. Yay. Multiple Disqus commenting on one page with minimal Ajax loading.
Here is the structure et al that is almost working for me. Only 2 bugs left. First is the secondary load when emptying, then reloading the new Disqus page into the Ajax element using the .ajaxComplete() callback function.
What's happening now is the callback is basically not being fired at all. As far as I can tell. Clicking on it a second time however, does make the call. But this is due to the class parameters being met for the else statement.
Second bug left is I'm having a hard time figuring out how to get the appropriate elements to enlarge, while leaving the others the same size.
// Load comments and/or custom post content
$(".boxyComments a").click(function (event) {
event.preventDefault();
$.ajaxSetup({cache:false});
var post_id = $(this).attr("rel"); var excHeight = $(this).closest('.boxy').find('.initialPostLoad').height();
var postHeight = $(this).closest('.boxy').find('.articleImageThumb').height();
var postWidth = $(this).closest('.boxy').find('.articleImageThumb').width();
// close other comments boxes that may already be open
if($('.commentsOpen').length ) {
console.log('comments are open');
$('.bigBoxy').closest('.boxy')
.animate({height:(postHeight + excHeight)}, 500);
$('.showComments')
.removeClass('bigBoxy')
.removeClass('commentsOpen');
$('.commentsAjax')
.empty(function(){
$(this).closest(".boxy").find(".showComments")
.addClass("commentsOpen")
.addClass("bigBoxy");
$(".bigBoxy").find(".commentsAjax ")
.css("display","block")
.animate({height: "500px"}, 500)
.load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/ajax-post/",{id:post_id});
$(this).closest(".boxy")
.ajaxComplete(function() {
var excHeight = $(this).closest('.boxy').find('.initialPostLoad')
.height();
var postHeight = $(this).closest('.boxy').find('.articleImageThumb')
.height();
$(this).closest(".boxy").animate({height: (postHeight + excHeight)}, 500)
});
});
} else {
$(this).closest(".boxyComments").find(".showComments")
.addClass("commentsOpen")
.addClass("bigBoxy");
$(this).closest(".boxy").find(".commentsAjax")
.css("display","block")
.animate({height: "500px"}, 500)
.load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/ajax-post/",{id:post_id});
$(this).closest(".boxy")
.ajaxComplete(function() {
var excHeight = $(this).closest('.boxy').find('.initialPostLoad')
.height();
var postHeight = $(this).closest('.boxy').find('.articleImageThumb')
.height();
$(this).closest(".boxy").animate({height: (postHeight + excHeight)}, 500)
});
}
});
Okay, here's full working code to do what you want. You'll have to swap out a few placeholders for your actual code:
<script>
jQuery(document).ready(function($){$(".boxyComments a").click(function (event) {
event.preventDefault();
var post_id = $(this).attr("rel");
var postLink = "<?= site_url('/path/'); ?>"+post_id;
$("#myFrame").attr('src', postLink);
});
});
</script>
And sample divs & iFrame:
<div class='boxyComments'>
<a href='#' rel='some-url'>test link</a>
</div>
<div class=".commentsIframeBig">
<iframe id='myFrame' height="500px" width="800px" src=''>
</iframe>
</div>
Tested it locally and it worked no problem. You might have been running into issues with it not properly accessing the iFrame. If you can give the iFrame an id that makes it easier.
It's because you're declaring var postlink as a jQuery object. You just need to get it as a string that you can then pass to the iframe.
var post_id = $(this).attr("rel");
var postLink = "<?= site_url('/ajax-post-fold/'); ?>"+post_id;
UPDATE 2
Looks like the string shouldn't be included within the <?= get_site_url() ?> after all.
Instead I've created a few vars to affect it. Code updated below with answer:
var postDir = "\/ajax-post-fold\/";
var postLink = "<?= get_site_url(postDir); ?>"+"\/ajax-post-fold\/"+post_id;

JavaScript: Replace element with content from another HTML

I would like to solve the following problem: Given a link on a Web page, I would like to replace the content of a specified div element with the content of a div element of another page. Say, just load the text "Stand on the shoulders of giants" from the Google Scholar page into my existing div element.
Up to date, if implemented the following example:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
Click me
<div id="myid">Text to be replaced</div>
<script type="text/javascript">
$("a").click(function() {
$.get(this.href, function(data) {
$("#myid").replaceWith($(data).find("#fb-root"));
});
previous_page = location.href;
window.history.pushState({page: $(this).index()}, $(this).html(), $(this).attr('href'));
return false;
});
window.onpopstate = function(event) {
location.reload();
}
</script>
</body>
</html>
I've included window.history in order to change the URL in the location bar, and to allow the user to restore the previous state of the Web page without the new content.
Now, I have two issues:
The replacement of the <code>div</code> element seems not to work, since the entire page from WhatIsMyIP is loaded.
While using Chrome, the entire page gets reloaded again and again right from the beginning. I think, the event window.onpopstate is triggered continuously.
Thank for any help!
You could combine a click and a $.load on a hyperlink:
$('a').click(function(e){
$('#myid').load($(this).attr('href'));
e.preventDefault(); //needed to prevent navigation!
});
If you want a special element within the page, you can append any selector. Example:
$('#myid').load($(this).attr('href') + ' div');
This will append all divs of the requested page.
Regarding your first issue
Try this
$('#myid').load(this.href + ' #fb-root');
instead of this
$.get(this.href, function(data) {
$("#myid").replaceWith($(data).find("#fb-root"));
});
Try to add event.preventDefault() before return false;
If I understand you correctly, you just want to replace the content of a specified div element on page1 (in this case div element with ID "myid") with the content of a div element from page2 (page2 is http://www.whatsmyip.org/).
Hope this might help:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
Click me
<div id="myid">Text to be replaced</div>
<script type="text/javascript">
$("a").click(function() {
$.get(this.href, function(data) {
var target_element_id_page2 = "element_id_page2";
var target_element_type_page2 = "div";
var respond= $('<div>' + data + '</div>');//You forgot this... It won't work unless you use it...
var target_element = respond.find( target_element_type_page2 + '#'+ target_element_id_page2 )[0]; //There "might" be more div elements with the same id: that's why you specify index
var container = document.getElementById( "myid");
container.innerHTML = target_element.innerText;
}, "html");
</script>
</body>
</html>
I took out window.history.pushState and window.onpopstate to better answer your question without any errors these two codes might give. If you put these back it should work perfectly. Althought I do not understand why you're using " previous_page = location.href; ". previous_page is not declared and you are not using it afterwards. Correct me if I am wrong...

document.write < won't work unless I use < what can I do instead to generate a link?

this code only seems to work when I use < instead of < and > instead of > so how can I get it to work so that it links to the rightful video owner's channel.
<script type="text/javascript">
function youtubeFeedCallback(json){
document.write("<a href='youtube.com/user/"+json["data"]["uploader"]+"'>"+json["data"]["uploader"]+"</a>");
}
</script>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/4TSJhIZmL0A?v=2&alt=jsonc&callback=youtubeFeedCallback&prettyprint=true"></script>
var text = json["data"]["uploader"],
url = "youtube.com/user/" + text;
text.link(url);
it would probably be better to use another injection method than document.write(), such as:
<script type="text/javascript">
function youtubeFeedCallback(json){
var user = json.data.uploader,
a = document.createElement("a");
a.href = 'http://www.youtube.com/user/' + user;
a.appendChild( document.createTextNode(user) );
document.getElementsByTagName("body")[0].appendChild( a );
}
</script>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/4TSJhIZmL0A?v=2&alt=jsonc&callback=youtubeFeedCallback&prettyprint=true"></script>
you may need to change the location the link gets inserted in, but the idea is to move away from document.write() and use pure DOM insertion.
hope that helps. cheers!
json["data"]["uploader"] may contains some invalid characters that spoils your html code. (Such as a single quote)

Categories