How to make html div embedable using JavaScript? - javascript

I want to provide simple web service and let anyone to embed it in any site using JavaScript.
The Service is to provide Visitor IP address for Static Websites or any one that wants to used JavaScript for showing IP address instead of Server-Side script.
my code is:
<div style="white-space:normal; display:inline-block;background-color:white">
Your IP Address is: <br><strong>
{ip}</strong><br>Country:{country}<br>
ISP:{isp}
</div>
Screen Shot:
I can use document.write() and output this content, but I am not sure if its the best choose, or using another method like appendChild to a parent element?
last note, should I enclose the script between window.onload()?

You could use good old VanillaJS. By just giving it an ID, then changing its innerHTML.. Its basically Javascript DOM. It changes the actual html Learn More here.
document.getElementById("IP").innerHTML = "XXX.XXXXX.XXXX";
document.getElementById("Country").innerHTML= "U.S.A";
document.getElementById("ISP").innerHTML= "ISP Name";
<div style="white-space:normal; display:inline-block;background-color:white">
Your IP Address is: <span id="IP"></span><br>
Country:<span id="Country">{country}</span><br>
ISP:<span id="ISP">{isp}</span><br>
</div>
So i get the id by doing the usual document.getElementById.. Then you can change its innerHTML By doing .innerHTML.
EDIT
Here is a codepen!
EDIT2
So now i understood you want to do this using document.write(); Well its going to be kinda tedious but this is preety much the overall result..:
<h1>Representation</h1>
<div style="white-space:normal; display:inline-block;background-color:white">
Your IP Address is: <span id="IP">
<script>
document.write("XXX.XXXXX.XXXX");
</script></span>
<br>Country:
<span id="Country"><script>
document.write("U.S.A");
</script></span>
<br>ISP:
<span id="ISP"><script>
document.write("ISP Name");
</script></span>
<br>
</div>

Related

parse <script> tag with js/jQuery

I have a HTML page where a user is able to edit a HTML resource (using ACE Editor). Within this HTML source, there is a <script>-tag, which does some pretty basic stuff.
Is there any elegant solution to parse the script tag in order to (e.g.) evaluate the variables used within the script tag? For "normal" tags I use parseHTML() to have the html as a jQuery object.
From this example, I would like to retrieve the value of $myVal (which is "f00") and write it to #myLabel:
<textarea id="myScript" rows="5" readonly>
<script>
$myVal = "f00";
</script>
</textarea>
<label id="myLabel">Hello</label>
$(function(){
$scriptVar = $('#myScript').text;
// parse the $scriptVar
// retrieve the value of, $myVal, write it to #myLabel
//$myParsedValue = ???
//$('#myLabel').text('bar!');
});
And here is the fiddle: https://jsfiddle.net/stepdown/jqcut0sn/
Is this possible at all? I don't really care about vanilla js, jQuery, regex or maybe even an external library for that purpose.
Thanks to #JeremyThille, who pointed me to the right direction. I found out, what I want to achieve is possible through jQuerys $.globalEval() - see the official documentation.
Basically what globalEval() does: it runs the script which is written in the <textarea> and makes the variables / functions globally accessible.
IMPORTANT: this implies, that syntax errors (etc) by the user will break the evaluation, and sequential functionality could be flawed. Also, the new variables are GLOBAL, so basically a user could rewrite scripts on the hosting page. (In my case both problems are of minor importance, since this is an internal application for trained users - they also have syntax highlighting through the amazing ACE editor. But I wanted to make sure to point it out. Also, there are several articles regarding the risks/ouch-moments when using eval()...)
I updated the fiddle to achieve what I wanted: https://jsfiddle.net/stepdown/Lxz7q6uv/
HTML:
<textarea id="myScript" rows="5" readonly>
$myVal = "f00";
</textarea>
<hr />
<label id="myLabel">Hello</label>
Script:
$(function(){
var myScriptContent = $('#myScript').text();
$.globalEval(myScriptContent);
console.log($myVal);
$('#myLabel').text($myVal);
});

css selector code to scrape/parse data from tricky website

Im having difficulty developing an adequate "CSS selector" code to scrape/parse the odds for the following HTML. I am relatively new to node.js. but ive successfully scraped similar websites in the past. Unfortunately this website is a little more tricky(for me anyway!). I can tell the problem must be the CSS selector code im using. could you please show me how to write a code that allows me to scrape the odds 11/2 from..
<div class="market"..............>
<header class=..........>
<div class="market-content">
<div class ="selection">
<div class="selection name" data- bind="html:selection.getTitle()"> Aston Villa </div>
<selection-button params="....>
<div>
<div class="odds-button"..........>
<span class="price">
<span class="odds-convert"......> 11/2 </span>
Hard to say with just that snippet of HTML, but for that (using jQuery):
$('.odds-button > . price > .odds-convert').text();
Of course it could be that selector matches somewhere else too, then you'd have to make it more specific by including a longer path. However, making it too specific from the get go makes it too brittle if the structure of the HTML changes.
I don't know exactly how you're scraping the content in Node.js, which libraries or techniques you're using, but this is how I'd do it client-side:
var oddsElement = document.querySelector([
".market",
".market-content",
".selection",
// obviously, change below to match your data attribute
".selection.name[data-SOME_KEY=\"SOME_VALUE\"]",
".odds-button",
"span.price",
"span.odds-convert"
].join(" "));
if (typeof oddsElement === "object") {
var odds = (oddsElement.textContent || oddsElement.innerText);
// or could use "let" keyword in strict-mode Node.js for block-scope
} else { // no match
console.warn("Odds cannot be found.");
}

Inject html after review widget loads for schema markup

My webstore uses Kudobuzz for product reviews, but our e-commerce platform (PDG) isn't supported for SEO markup data.
This widget does not support schema markup on it's own, so I want to somehow select the relevant pieces and inject the schema markup to the various divs/spans that make up the widget. One problem is figuring out how to inject code that google can parse, and another is figuring out how to make the actual selectors for this super bloated widget.
Here is a codepin of the widget and some markup data that is already on the site: http://codepen.io/anon/pen/GpddpO
Here is a link to a product page if you want to see how everything works: https://www.asseenontvhot10.com/product/2835/Professional-Leather--Vinyl-Repair-Kit
This is (roughly) the markup I'm trying to add if it helps:
<div itemscope itemtype="http://schema.org/Review">
<div itemprop="reviewBody">Blah Blah it works 5 star</div>
<div itemprop="author" itemscope itemtype="http://schema.org/Person">
Written by: <span itemprop="name">Author</span></div>
<div itemprop="itemReviewed" itemscope itemtype="http://schema.org/Thing">
<span itemprop="name">Stop Snore</span></div>
<div><meta itemprop="datePublished" content="2015-10-07">Date published: 10/07/2015</div>
<div itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating">
<meta itemprop="worstRating" content="1"><span itemprop="ratingValue">5</span> / <span itemprop="bestRating">5</span> stars</div>
</div>
Theoretically you could write a very small amount of microdata using css :before and :after - with content but it would need all spaces and symbols converted into ISO format, eg.
#name:before { "\003cspan\2002itemprop\0022name\2033"}
#name:after { content: "\2044\003cspan003e"
even spaces need to be substitued with \2002 or an equivalent whitespace
code
should wrap this microdata to your HTML to any element called name:
<span itemprop="name">...</span>
Clearly this can only work if the widget lets you have clear ids or class names for the elements added, and it may be useless you know the type of object reviewed first (eg Book, Movie, since this needs to go at the start in the example I gave - which is incomplete). The code would need to be nested correctly so if you want further help can you edit your question with example HTML for a completed review.
Writing your own JSON-LD script at the top of the page is another option - it would be a different question (if you get stuck) but isn't embedded within the data itself
Edit
it's a good idea to test the css in a separate environment first, eg setup a jsfiddle

Are they any syntax highlighting plugins that will allow you to embed an ignorable html element into a snippet?

I am trying to make dynamic code examples for our api that can be constructed from from input html elements.
A paired down example looks like this, I give the user an input to name the device they would like to create.
<input class="observable-input" data-key="deviceName" type="text" value="deviceKey" />
I would then like that input to update code examples (replacing the device name in the example with the one the user inputs).
<code lang="python">
device = { "name": "<span data-observeKey="deviceName">Name</span>" }
client.createDevicewrite(device)
</code>
I have all of the code setup for observing a change in the input and updating the code examples, this works great. All of the syntax highlighters I have looked at, usually chop the snippet up and rerender the example wrapped with its own html (for styling). Is there an option/configurable way to get a syntax highlighter to not strip the these tags, or is there a different approach I should be looking at for preserving the syntax highlighting and still supporting dynamic updates without having to do a full text search of each snippet's rendered tags.
The example output of the pygment (current syntax highlighter I'm using).
<li>
<div class="line">
<span class="n">device</span>
<span class="o">=</span>
<span class="n">{</span>
<span class="s">"name"</span>
<span class="p">:</span>
<span class="s">"Name"</span>
<span class="n">}</span>
</div>
</li>
I decided to just go with a brute force approach, it ended up being decently performant, ill leave my code here if anyone is interested in what I did
https://gist.github.com/selecsosi/5d41dae843b9dea4888f
Since i use backbone, lodash, and jquery as my base app frameworks the gist uses those. I have a manager which will push updates from inputs to spans on the page which I use to dynamically update the code examples

change text string on couple website at the same time using jquery

22I am preparing a website which will contain prices of products on couple pages. Sometimes the same products are on couple of pages (e.g. on the main page and the specific product page). What I'm trying to achieve is to have ability of using any sort of spreadsheet or any other type of document (another perhaps) to control prices of all items across the whole website. I believe every price must be indexed somehow so we know that in with id="product1" will be the correct price and different than in id="product2".
Currently I have the example code here:
<h3>Product 1</h3>
<div class="price">
<span id="product1">£55 per day</span>
</div>
<h3>Product 2</h3>
<div class="price">
<span id="product2">£20 per day</span>
</div>
etc...
Sorry for rather a 'question type' topic than the 'case type', but I was trying to find the solution already. I know it can be done in php, but I have no idea about php unfortunately. So anything in html / javascript will be handy. Thnx a lot for any help/advice.
use JSON, not XML It's not 2003. Your jquery would be:
var prices = $.get("prices.json")
var product;
$("h3").each.( function()
{
product = $(this).html();
$(this).next().children("span").html(prices[product]);
});
Assuming you have no other H3's on your pages, otherwise give each product ID 'h3' a class a la:
<h3 class="products">Product 1</h3>
and use $(".products") instead of $("h3").
You could also use a selector to pull the <div>'s by class, and fetch the child <span>'s id.
I would recommend storing the data in either a database or an xml file to be read by the website. That way it's a "change once" situation. However, the scope of what needs to be done is beyond what you'd find in a simple answer here.
Edit: Jquery is a client side language, which means that it will only change what's currently exposed to the client at that time. It does have the ability to read from an xml file, and use that data to populate the display. But that data does need to be stored externally for it to affect more than one page at the same time.

Categories