Adding Javascript Widget to a Single Tumblr Post - javascript

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.

Related

I can't grab specific URL in search page

I enter the estate website and searched by name of the city. After that I want to grab Osaka City building URL. In here http://brillia.com/search/?area=27999 There are four of those. 
And I m using that link to grab URL.
$allDivs = $parser->getElementsByTagName('div');
foreach ($allDivs as $div) {
if ($div->getAttribute('class') == 'boxInfomation') {
$allLinks = $div->getElementsByTagName('a');
foreach ($allLinks as $a) {
$linkler[] = $a->getAttribute('href');
}
}
}
But I cant grab those. Actually I grabbed not just osaka city pages URL actually grabbed all of it. When I try to see the source the osaka page site. It shows http://brillia.com/search/ Thats why I m grabbing all other links...
But how can I grab just URLs in here -> http://brillia.com/search/?area=27999
Any idea? Thank you.
Can you do this by using jQuery? in that case this grab the a href
$("div h3 a").each(function(){
var link = $(this).attr("href");
console.log(link);
});
here a jsfiddle test
The parser relies on libxml to extract elements but that page is using html5 heavily, ommiting certain close tags, etc and that isn't really strict xml, so it's struggling to "correct mistakes" by guessing where to close missing tags, returning wrong results.
You need a parser with html5 support like HTML5DOMDocument that extends DOMDocument and should have mostly the same interface.

How do I render text on the page of other sites (once script planted)

I am learning javascript and trying to build a chat app like intercom.
How do i go about creating a popup on another page once my js script is planted??
I do it locally like so:
function Hide()
{
document.getElementById('div1').style.visibility="hidden";
}
There is many way to do it i'll explain the idea with some examples, let's go
Our code based on two functionalities:
1: innerHtml = "<YOUR CODE/>"; This property is for injecting the html in the element more info.
2: document.getElementById("IdName") This property is for selecting and element wich we will apply some functionalities, in our case is the property N°1 more info.
3: <div id="IdName"></div> Here where we will append our html or text more info.
Now we start with some examples:
1st example:
API File:
function function_name(argument) {
document.getElementById(argument).innerHTML = "<p>Paragraph example..</p>";
}
User File:
// first of all the user need to put a div with an attribute ID in his html where
//he want to append the html given by the API
<div id="IdName"></div>
//after that he must call the specified function wich is in our case function_name() and put the ID as argument
function_name("IdName"); // this will append the html in the div with the ID == IdName
Also you can use document.getElementsByClassName("className"); in place of ID
2nd example:
In this case the user don't need to put any additional html or any other things; in this example we will add our html into the body element wich is a necessary element in HTML page.
document.body.innerHTML += "<p>Paragraph example..</p>";

How to add HTML code to a different HTML file using JavaScript or PHP

Alrighty, so I am trying to make a little page on my website that takes a few values and then when you click a button, it adds those values inside of a div on a different HTML page.
My code is:
<input type="text" name="URL"><br>
<input type="text" name="ImageURL"><br>
<input type="text" name="Title">
<button onclick="addCode()">Submit</button>
So for the addCode() function I want it so that it adds the values inside of a the item div on a different HTML file just like:
<div class="item">
<div class="animate-box">
<a href=URL><img src=ImageURL></a>
<div class="fh5co-desc"><a style="TEXT-DECORATION:none; COLOR:#818892; LINE-HEIGHT:20px;" href=URL>Title</a></div>
</div>
</div>
Thanks in advance.
What you are doing is technically impossible. without some sort of persistence, that is;
you cannot edit a page you aren't on. web browsing is a stateless technology.
if you meant you want to fill out those inputs then redirect on click and have those values available, there are a few different ways to do it:
1) Query String
write your code on the second page in a way that it accepts params from a query string in the url bar
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
var textDecoration = getUrlParameter('textdec'),
color = getUrlParameter('color'),
lineHeight = getUrlParameter('lnheight');
then you can send the request for the page as
http://page.com/page?textdec="someval"&color="somecolor"&lnheight="someheight"
however this will not work if you are not going directly to that page after your current one
2) localStorage
on your first page set the local storage values:
localStorage.setItem('lineHeight', 'someVal');
localStorage.setItem('color', 'someColor');
localStorage.setItem('textDecoration', 'someVal');
then on your second page retrieve the values
var lineHeight = localStorage.getItem('lineHeight'),
color = localStorage.getItem('color'),
textDecoration = localStorage.getItem('textDecoration');
3) serverSide persistence
this will vary MASSIVELY depending on how you your backend is structured
but the general gist is make a post request (ajax or otherwise) &
collect the data on the backend
then when you render the second page send the variables that were posted, either through interpolation or included as script variables
The only way to do this (without getting other technologies involved) is to use the localStorage, storage event. And, even with this, it will only work when the two pages are coming from the same domain and are open in different browser tabs (of the same browser) at the same time.
If those conditions are present, then modifying localStorage on one page will fire the storage event, which the other page can be set up to listen for. The other page can then respond to the event by pulling new values (that the first page wrote into localStorage) out and placing them anywhere on the second page that you like.
This is the kind of solution that you might encounter if you were on a travel site with more than one browser tab open. You may be looking at different flight options in different tabs. If one tab's code has an update that any/all other open tabs should know about, this technique does the trick.
Here's an example of how to set values into localStorage and use them. But, localStorage doesn't work here in the Stack Overflow snippet environment, so you can run the code here.
Once the values are in localStorage, you can pick them up from any other page that is being served from the same domain. So, the "getItem" code I'm showing here would really be placed on your "page2.html".
// Get DOM references:
var name = document.getElementById("name");
var color = document.getElementById("color");
var airspeed = document.getElementById("airspeed");
var btn = document.getElementById("btnGo");
// Set up button click event handler:
btn.addEventListener("click", function(){
// Get values and place in localStorage
localStorage.setItem("name", name.value);
localStorage.setItem("color", color.value);
localStorage.setItem("airspeed", airspeed.value);
// For demonstration, get values out of localStorage
console.log("What is your name? ", localStorage.getItem("name"));
console.log("What is your favorite color? ", localStorage.getItem("color"));
console.log("What is the airspeed of a laiden swallow? ", localStorage.getItem("airspeed"));
// If you wanted to redirect the user to the second page, now that the intial values
// have been set, you could just do:
location.href = "path to second page";
});
<div>What is your name?<input type="text" id="name"></div>
<div>What is your favorite color?<input type="text" id="color"></div>
<div>What is the airspeed of a laiden swallow?<input type="text" id="airspeed"></div>
<button id="btnGo">Go!</button>
If you're trying to edit the actual source code of the file, you'll need something like PHP. Otherwise, JS is just fine.
PHP Solution
You could use something like this:
<?php
$old = file_get_contents("some_page.html");
$content = explode("<span>",$old,2); // replace <span> w/ opening tag
$content = explode("</span>",$content[1],2); // replace </span> w/ closing tag
$data = "new content of element";
$new = str_replace($content[0],$data,$old);
?>
Updated JS Solution
You can't use my previous solution. Instead, you would have to create a function in the second HTML file that could be called from the first file, like this:
A script in file2.html:
function set(id,val){
$("#"+id).html(val); // jQuery
document.getElementById(id).innerHTML = val; // pure JS
}
A script in file1.html:
var win = window.open("http://example.com"); // open the window
win.set("some_id","Some content.") // the function that we set earlier
Note that this is reverted once the user closes or reloads the tab, and only applies to that user and that tab.

How would I make a self-linking <div>?

After much Googling, I resort to the chance at ridicule and moderation on Stack Exchange.
What I am trying to do sounds simple enough. I want to make a <div> id/class that will link automatically create a link to itself via some kind of scripting.
Let me put down some pseudocode, before I make it sound more complicated than it is:
#Let div.link = xxx.html
#Let div.pic = xxx.png/jpg
for div in HTMLdocument:
if div.class == "autolink":
div = "<img src=\"mysite/" + div.pic + ">"
Now, obviously that's Python pseudocode, but I am familiar(ish) with PHP and Javascript. Basically, I want to make the div generate an HTML link without having to actually type out the tags and links for every given div on a web page. I want to be able to type, in my index.html:
<html>
<head></head>
<body>
<div class = "1"></div>
<div class = "2"></div>
</body>
</html>
and then to be presented with a page that has the two divs linked, imaged, and, preferably, formatted.
Like I said, the problem seems simple, but I can't seem to get it to work right, in any language. This seems like a thing that would be very useful for begiiner web designers.
PERSONAL NOTE:
I would preferably like to see a solution in PHP or Javascript, but if you are good with Django and want to show me how to get it done in that, I would be just as grateful!
=========================================
EXAMPLE:
Let's say you have a browser based RPG, and you want to show your player's inventory. The Inventory page would display the items in a players inventory, complete with a link and image, based on whatever was in that user's inventory page. It would look like this (this is VERY rough output, Statements tagged in #these# are not code, and should be interpereted as what they describe):
<h1>User's Inventory:</h1>
<p><div class = "item_1">#Link to page of 'item_1', image of 'item_1'#</div></p>
<p><div class = "item_2">#Link to page of 'item_2', image of 'item_2'#</div></p>
The above would display, roughly, a header that said "User's Inventory", and then display a linked image of item_1, followed by a newline and then a linked image of item_2, where said items would be in a separate file OR a list that lists all the items and their respective links and images.
You can use jquery, and when page dom is loaded, you cycle through each div that has the class autolink and do your manipulations (add your desired html into each div). You can use the id of each div to place data inside. You can use a prefix to that id values for different types of data. For example, im using "inventory_" as a prefix.
<h1>User's Inventory:</h1>
<p><div class = "autolink" id="inventory_item_1">#Link to page of 'item_1', image of 'item_1'#</div></p>
<p><div class = "autolink" id="inventory_item_1">#Link to page of 'item_2', image of 'item_2'#</div></p>
then jquery on document ready:
<script type="text/javascript">
$(document).ready(function ()
{
// define your website here
var mysite = "http://www.example.com/";
// this will cycle through each div with class autolink. using `this` to reffer to each.
$(".autolink").each(function () {
// we get for div with id="inventory_item_1" ...
var mylink = $(this).attr('id').replace("inventory_",""); // ... a value item_1
var myimagesrc = $(this).attr('id').replace("inventory_","image_"); // ... image_item_1
$(this).html('<img src="'+mysite+'images/'+myimagesrc+'.jpg">');
// the above will add html code of this format:
// <img src="http://www.example.com/images/image_item_1.jpg">
});
});
</script>
try it here:
http://jsfiddle.net/5APhT/2/
I'll give a sample in php. Here is an example if you already have a set of links to use
<?php
//Create a multidimensional array to store all you need to create links
$links['1'][]="http://www.yahoo.com";
$links['1'][]="yahoo.com";
$links['2'][]="http://www.facebook.com";
$links['2'][]="yahoo.com";
$links['3'][]="http://www.google.com";
$links['3'][]="yahoo.com";
foreach($links as $class => $innerArray){
$link=innerArray[0];
$linktext=innerArray[1];
echo "<div class='$class'><a href='$link'>$linktext</a></div>";
}
?>
This creates the divs for you so you don't have to add them in advance.
You can add images in the same manner

Jquery .html and .load

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.

Categories