I'm trying to teach myself jQuery and I'm a little stomped with the load() method. I'm working on eBay listings. Yes, I know includes are not allowed on ebay. However, there is a workaround that has been around for a few years and ebay doesn't seem to be cracking down on it.
var ebayItemID='xxxxxxxxxxxxxx'; // This is eBay code. I cannot edit it.
<h1 id="title"> TO BE REPLACED</h1>
$(document).ready(function(){
var link = "http://www.ebay.com/itm/" + ebayItemID + "?item=" + ebayItemID + &viewitem=&vxp=mtr";
var newTitle = $('#title').load(link + "#itemTitle");
$('#title').html(newTitle);
});
What's the point of this. I want to show the item title on the description, but I want to do so dynamically,
load will not work on different domains (ebay on your case)
load will set the content directly to your element. You can't assign it to a var.
If you would like to indicate you want to extract content from a specific element you need to add a space between your link and the element id:
You can find more info on the jQuery docs
$('#title').load(link + ' #itemTitle', function() {
alert('Load was performed.');
});
When you use load will place the returned html into the element(this case #title).
So you don't need to call html after it.
Related
I only do scientific programming so I am not too familiar with javascript. I am trying to add a widget to one single tumblr post. The website I got the widget from makes it specifically for tumblr and it is:
<div class="shopthepost-widget" data-widget-id="4665345"><script type="text/javascript">!function(w,i,d,g,e,t){d.getElementById(i)||(element=d.createElement(t),element.id=i,element.src="https://widgets.rewardstyle.com"+e,d.body.appendChild(element)),w.hasOwnProperty(g)===!0&&"complete"===d.readyState&&w[g].init()}(window,"shopthepost-script",document,"__stp","/js/shopthepost.js","script")</script><div class="rs-adblock"><img src="https://assets.rewardstyle.com/production/424ab6aff12fe31b5b93d8f5ce7cc70d2953e565/images/search/350.gif" onerror='this.parentNode.innerHTML="Disable your ad blocking software to view this content."' style="width: 15px; height: 15px"><noscript>JavaScript is currently disabled in this browser. Reactivate it to view this content.</noscript></div></div>
If this is added to the actual theme on tumblr, it works great. However, I am trying to put this in just one post on tumblr. When I'm trying to make the post I will go to the html and add it in there but it will not actually show up on the site. Any tips on how to solve this? Thank you in advance.
You have two choices available to you.
First: If you can host the javascript file somewhere remotely you can link it in the bottom of the post via the editor. The beauty of this is that you can update the js without having to update your main template.
For post edits you can select settings and choose HTML markup
then add a link to the script in the bottom of the page.
Or for a page edit it is the same concept you can switch to HTML markup and add it there.
Second: you can create a function in your template and then only fire it on the relevant post or page.
The way I have done this in the past is to get the post/page name from the file path, split the file path into an array and add them to the classnames for the html element. Example here:
const dom = document.querySelector('html');
const path = document.location.pathname.split('/');
const primaryDir = path[1]; // get the primary folder
const secondaryDir = path[2]; // get secondary folder
const tertiaryDir = path[3]; // get the tertiary folder
const setIndexPage = () => {
if (!primaryDir) { // if there is no primaryDir we should assume we are on the home/index page
dom.classList.add('index');
} else if (tertiaryDir) {
dom.classList.add(primaryDir + ' ' + secondaryDir + ' ' + tertiaryDir);
} else if (secondaryDir) {
dom.classList.add(primaryDir + ' ' + secondaryDir);
} else {
dom.classList.add(primaryDir);
}
}
Now we can target our function to run only if it finds the correct selector
if (document.querySelector('.yourClassName').length) {
// run your function here
}
For .yourClassName you need to pass in the page or post name. By default Tumblr will create a unique post id (integer) and add that to the filepath. But you can also use text/verbose file names in addition.
The beauty of this method, is that the classnames will be added to every page, but you can chose to target only certain posts/pages with your js function.
Alternatively you could use this method and add the html selector only to your post/page content. So wrap your content in a div and give that a unique id or classname, but the method is the same.
Here is an example of a page where I am doing this (although I am concatenating the class names slightly differently).
I hope this makes sense.
I need to put a link out from a corporate site to a surveymonkey survey. Our site uses a proprietary CMS limiting me from adding any proper function or third party plugin.
After evaluating options like those exposed in this other question, I believe I call the correct javascript function but everytime I open my CMS, the link duplicates itself... leading me to think I've done something inapropriate.
Things look acceptable on the JSFiddle demo I put together for this question but I'm hoping you'd have a more elegant solution in mind so I could try options !
<script type="text/javascript">
document.write("<a href='https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname + " target='_blank'>Test - survey</a>");
</script>
Try this - it will probably not do what you want in one go, but it will hopefully isolate your problem so that you can better pinpoint what's going wrong:
HTML:
<div id="link"></div>
Javascript:
var SURVEYID = 3
var a = document.createElement("a");
a.innerHTML = "Test - survey";
a.href = "www.surveymonkey.com/r/"
+ SURVEYID
+ "?url="
+ window.location.pathname
+ "&target=_blank"
document.getElementById("link").appendChild(a)
I'm afraid there can be multiple things going wrong, but I hope you can now distinguish between the various parts that your URL is built up from.
This is mostly just a theory because I don't know your CMS or how it works, but I'm assuming that the CMS is inlining the javascript, executing it, and retaining that as its content along with the script. This would create that duplication. The original intent of using document.write I would assume was to completely replace the content; but if it's inlined, it only appends. An external script would completely replace. See below:
All of this text is retained.
<script type="text/javascript">
document.write("<a href='https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname + "' target='_blank'>Test - survey</a>");
</script>
In this demo, we use document.body.innerHTML instead. This will replace the content completely.
None of this text will be retained.
<script type="text/javascript">
document.body.innerHTML = "<a href='https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname + "' target='_blank'>Test - survey</a>";
</script>
If true, complete replacement of the body content is your goal, innerHTML is probably what you need.
Edit + Warning:
This may make the page inaccessible from the CMS depending on how it's built. It may make editing the page impossible.
Edit
Here's a better solution. Just set the href of the anchor by first getting it by the ID. This was based off of Sven ten Haaf's Answer.
<a href="#" id="__smlink" target='_blank'>Test - survey</a>
<script>
document.getElementById('__smlink').href = "https://www.surveymonkey.com/r/[SURVEYID]?url=" + window.location.pathname;
</script>
A friend and I are trying to learn jQuery, and we've come across a problem we just can't figure out. We're trying to use WhateverOrigin to scrape some data from a forum (we have permission to do so from the owner, he set up a test post for us to practice scraping on). The HTML we're working on is this:
<div>
<span id="msg_68" class="subject_title">
TEST: SCRAPE THE URL
</span>
</div>
Using WhateverOrigin, we can successfully pull the complete HTML of the site using
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('[INSERT URL HERE]') + '&callback=?', function(data){
alert(data.contents);
});
However, when we tried to pull that specific element's HTML or text (to check we were pulling the correct data) we either got "undefined" with html or "" with text.
The code we were using to pull it was this:
$(document).ready(function(){
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('[INSERT URL HERE]') + '&callback=?', function(data){
alert($("#msg_68 a").text());
alert($("#msg_68 a").html());
});
});
any ideas?
Thanks
When you write $("#msg_68 a"), you are trying to access this element from the DOM in your current page and not from the loaded data.
You need to select #msg_68 a elements, within the data.contents, you can either :
Parse this data into a DOM element then fetch it to get the required element:
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('[INSERT URL HERE]') + '&callback=?', function(data){
var div = $("<div><div/>");
div.html(data.contents);
alert($("#msg_68 a", div).text());
});
Or just refer to it directly with data.contents as the content is a valid HTML:
alert($("#msg_68 a", data.contents).text());
By using $("#msg_68 a") you are selecting an element from the DOM. That element is not in the DOM yet, it is stored in a variable at that moment after you get the data from ajax. To select it like that, you'd have to first insert data from ajax to your DOM. Your alternative is the "filter" function or searching within the 'data' variable context (depending on your jquery version)
Option 1:
$(data.contents).filter('#msg_68 a');
Option 2:
$("#msg_68 a", data.contents);
Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.
For example, within the target HTML is the tag:
<div id='news-header'>Big Day in Wonderland</div>
So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
I'm having trouble figuring out how to access the non-current document in JS.
Thanks in advance for your help.
ADDED: Firefox style issue (see comment below).
I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard getElementById to pull out the piece you want. For example:
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = '<body><div>Nonsense</div><div id="news-header">Big Day in Wonderland</div><p>pancakes</p></body>';
var h = doc.getElementById('news-header');
// And now use `h` like any other DOM object.
Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/
Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.
<a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>
$(function() {
var a = $('#mylink');
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a $('a').each() loop and call it a day.
update to support multiple links on condition:
$(function() {
$('a[linked_div]').each(function() {
var a = $(this);
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
});
The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.
You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method
I am trying to avoid hard-coding each instance of this WYSIWYG editor so I am using jQuery to create an each() loop based on function name. Annoyingly InnovaStudio seems to explode when I try.
Documentation
Attempt #1
<script type="text/javascript">
/*
id = $(this).attr('id');
if(id.length == 0)
{
id = 'wysiwyg-' + wysiwyg_count;
$(this).attr('id', id);
}
WYSIWYG[wysiwyg_count] = new InnovaEditor('WYSIWYG[' + wysiwyg_count + ']');
WYSIWYG[wysiwyg_count].REPLACE(id);
*/
var demo = new InnovaEditor('demo');
demo.REPLACE('wysiwyg-1');
console.log('loop');
</script>
Effect
Works fine, but of course only works for a single instance of the editor. If I want multiple instances I need to use an each.
Attempt #2:
<script type="text/javascript">
var wysiwyg_count = 1;
//var WYSIWYG = [];
var demo;
(function($) {
$(function() {
$('.wysiwyg-simple').each(function(){
/*
id = $(this).attr('id');
if(id.length == 0)
{
id = 'wysiwyg-' + wysiwyg_count;
$(this).attr('id', id);
}
WYSIWYG[wysiwyg_count] = new InnovaEditor('WYSIWYG[' + wysiwyg_count + ']');
WYSIWYG[wysiwyg_count].REPLACE(id);
*/
demo = new InnovaEditor('demo');
demo.REPLACE('wysiwyg-1');
console.log('loop');
});
});
})(jQuery);
</script>
Effect
Replaces the entire HTML body of my page with JUST WYSIWYG related code and complains as no JS is available (not even Firebug, so can't debug).
Notice that I am hardcoding the name still. I only have one instance on the page I am testing it on, so when I get this hard-coded name working I will get the commented out code working along the same lines.
Does anybody know what the hell is going on here?
Solution: Don't bother trying to use InnovaStudio, went with CKEditor instead.
Even though you went for CKEditor you might be interested in a solution. You can supply a second argument to the REPLACE function. This second argument should also be a id, id from a element able to accept html output (like div, span, p).
demo = new InnovaEditor('demo');
demo.REPLACE('wysiwyg-1', 'wysiwyg-1-replaceDiv');
When the second argument is left out, InnovaStudio, writes the html output to the document by simply using:
document.write();
Hope this helps!
Why don't you use their own initialization code since version 4.3:
<textarea class="innovaeditor">
content here...
</textarea>
<script>
oUtil.initializeEditor("innovaeditor",
{width:"700px", height:"450px"}
);
</script>
The method is oUtil.initializeEditor(selector, option). The first parameter is selector and second is editor properties in JSON format.
The selector can be:
Css class name, if class name is specified all textareas with specified class name will be replaced with editor.
Textarea Id. If it is an Id, a prefix '#' must be added, for example oUtil.initializeEditor("#mytextarea").
Textarea object.
The second parameter is editor's properties. All valid editor's properties can be specified here for example width, height, cmdAssetManager, toolbarMode, etc.
Note that this method can be called from page onload or document ready event or during page load (as long as the object referred by selector are already rendered). This method available automatically when the page include the editor script.