I have a JavaScript file where I need to create some kind of dictionary (containing translated text) from a html page, and to be able to change language from the HTML header.
<a class="text-center" id='lnkHumanResources'>
<p><img width="100" height="100" src="assets/img/icons/home-hr.png" /></p>
<h1>Ljudski resursi</h1>
</a>
This is an example of code containing the string which needs to be translated
"Ljudski resursi" to "Human Resources".
So, I need to have some hard - coded text on different languages in .js file, and some kind of method to change language from HTML header, and include it to few HTML pages that need to be able to change language.
Solved
Whoever gets stuck with same kind of problem, see Translate.js
Download plugin and unzip it into your lib folder, and include it to all html pages you want to translate
<script src="assets/js/lib/translate.js-master/jquery.translate.js"></script>
I also created dictionary.js containing all strings I wanted to translate from all pages on few languages, and included it also to all html pages that needed to be translated
var dict = { // dictionary.js
"Home": {
pt: "InÃcio",
en: "Home"
},
"Download plugin": {
pt: "Descarregar plugin",
en: "Download plugin"
}
};
Include to html example:
<script src="assets/js/lib/dictionary.js"></script>
Don't forget to wrap all hard coded strings with span attribute with class "trn"
<p class="some-class"><span class="trn">Text to translate</span></p>
Then just add next line in html pages and you're good to go :)
var translator = $('body').translate({lang: "en", t: dict}); // en to use English
you can use text function of jquery to change the content of the h1
$('#lnkHumanResources h1').text("Human Resources");
dont forget to link the JQuery to your Html page
Related
In my university course/module that covers intermediate HTML and CSS, and basic java-script (thought we haven't gotten there yet): I need to create a website using HTML, CSS and optionally java-script as bonus marks.
I am stuck at the gallery, I want to make a responsive image grid (that I can learn/get from https://www.w3schools.com/howto/howto_css_image_grid_responsive.asp); However I want to have a local folder filled with say 100 images and my website with html/css/js code that doesn't require me to manually hard code each individual image from the folder. In hindsight I want to add and remove images from said folder and have the website's gallery adapting to the added/removed images.
Theoretically I assume that I'll need to read in the folder's contents, into a list/array, then somehow parse them and output the content.
I have found two sources that touches on the idea:
- https://www.html5rocks.com/en/tutorials/file/dndfiles/
- https://github.com/blueimp/JavaScript-Load-Image#meta-data-parsing
I have searched for a few hours and I would think that such a code should exist somewhere, thought I believe my lack of knowledge regarding html, css, js, etc and general terminology is hindering me in my search, thus any advice would be greatly appreciated.
Thank you in advance for your time and effort.
Consider using a shell script from the corresponding directory where source image files are present.
You can simply make a .cmd file with the following code and execute that, it would dynamically generate an html file where you can display images as you wish.
scriptToExecute.cmd
echo ^<!doctype html^>^<head^>^</head^>^<body^> >> index.html
for %%j in (*.JFIF, *.png, *.JPG, *.GIF) do echo ^<img src=^"./%%j^" style="width:176px;height:300px" ^> >> index.html
echo ^</body^>^</html^> >> index.html
index.html
<!doctype html><head></head><body>
<img src="./2.jfif" style="width:176px;height:300px" >
<img src="./3.jfif" style="width:176px;height:300px" >
<img src="./4.jfif" style="width:176px;height:300px" >
<img src="./1.png" style="width:176px;height:300px" >
</body></html>
You can make changes to the shell script to display the images in different elements such as a carousel, etc.
If you want to load images from a folder dynamically (not entering each manually) you can't avoid needing javascript. Adding jQuery into the mix makes it easier not harder. Don't be afraid of using jQuery even if you're only just starting to learn javascript.
To be able to use jQuery, all you need to do is add this:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Essentially what that does is add the $ variable which you'll see in the following code provides a straightforward way to make an ajax call and also to add new img elements to the body element.
To create an element for each image in the folder (assuming it contains only images) should be as simple as the following:
<script type="text/javascript">
var folder = "images"; //TODO: change this to the path to your folder with the images.
$.ajax({
url: folder,
success: function(data) {
$(data).find("a").attr("href", function(i, val) {
$("body").append("<img src='" + folder + '/' + val + "'>");
});
}
});
</script>
Alternately, if you just want to avoid having to type out all the img elements by hand and fill in each src attribute by hand, you can write a bit of javascript that automates that. Using the following script you'll be able to click 'Choose Files' and select all the images in the folder, click 'Open', and then click 'Go' and it will generate the html for all the img elements and display it. You can then copy that html and manually paste it into your real project.
<input id="file" type="file" multiple />
<button onClick="go()">Go</button>
<div id="output"></div>
<script type="text/javascript">
function go() {
const fileInput = document.getElementById('file');
const outputDiv = document.getElementById('output');
let html = '';
for (const file of fileInput.files) {
html += '<img src="images/' + file.name + '" />';
}
outputDiv.textContent = html;
}
</script>
https://codepen.io/rockysims/pen/MPEMOG
I've downloaded a Markdown JS library but I don't know if it supports syntax highlighting, or any of his two supported dialects (gruber/maruku), because its the first time I try to add markdown support to my webpages. So, I would like to know how to integrate a syntax highlighter (like Alex Gorbatchev's JS library) to markdown.
Any other libraries are welcome. Basically, my Markdown snippets are in .md files loaded that way:
<div class="markdown-f">
<?= file_get_contents("file.md"); ?>
</div>
and it contains code snippets together with common Markdown text. I need a JS library to be able of doing something like:
<script>
$('.markdown-f').each(function() {
var contents = $(this).text();
$(this).empty();
contents = markdown.toHTML(contents);
$(this).text(contents);
});
</script>
with a dialect or any other hacktrick supporting syntax highlighting (specifying manually the target language for example).
I've used that markdown parser on my website to display the README files of repos I've created. It wraps code blocks in <pre><code> code goes here </code></pre>
It does not use highlighting, but you could then use the other library you mentioned after calling:
$("code").addClass("brush: js") // assuming you want to highlight javascript
Finally I used highlightjs.
The #A.OzanEkici solution has the (little) downside that I lost the markdown highglighting of my text editor (the emacs's markdown-mode), since the contents inside the <pre> tag must be un-indent to don't see the indention in the rendered page, and the #JaredBeach doesn't work either because Alex Gorbatchev's library only work on <pre> tags, not on <pre><code> tags, which is what is replaced by the markdown syntax.
So, my solution was simply:
<script>
$('.markdown-f').each(function(){
$(this).html(markdown.toHTML($(this).text()));
});
hljs.initHighlightingOnLoad();
</script>
And that has the adventage that the language is automatically detected.
I use Alex Gorbatchev's JS library to do this and it works great.
First you should create a <pre> element like this;
<pre class="brush: __yourFileType__"> + data + </pre>
data refers to your contents and __yourFileType__ can be one of these .
Ex: class="brush: xml" , class="brush: txt"
After that you just simply call it;
SyntaxHighlighter.highlight();
I have been trying to save the source code of a section of a webpage using PHP. When I extract the content of whole webpage, the source code order is preserved but when I try to get part of the document using
$dom = new DOMDocument;
$dom->loadHTML($webpage);
$xpath = new DOMXPath($dom);
$query_tag = "//div[contains(#class, 'class-name')]";
$result = $dom->saveHTML($xpath->query($query_tag)->item(0));
The script tag gets messed up. Until now, this is the only website where this issue occurred. Are there some limitations of saveHTML function that I am not aware of?
This is what I should be receiving:
<div id="sponsored-category-header" class="page-header sponsored-category-header clear"> <script type="text/javascript">jQuery(document).ready(function($) {
var cat_head_params = {"sponsor":"SEO PowerSuite","sponsor_logo":"https:\/\/www.searchenginejournal.com\/wp-content\/plugins\/abm-sej\/includes\/category-images\/SPS_128.png","sponsor_text":"<div class=\"taxonomy-description\">Dominate Google local search results with ease! Get your copy of SEO PowerSuite and keep <a rel=\"nofollow\" href=\"http:\/\/sejr.nl\/PowerSuite-2016-5\" onClick=\"__gaTracker('send', 'event', 'Sponsored Category Click Var 1', 'Local Search', 'SEO PowerSuite');\" target=\"_blank\">your local SEO strategy<\/a> up to par.<\/div>","logo_url":"http:\/\/sejr.nl\/PowerSuite-2016-5","ga_labels":["Local Search","SEO PowerSuite"]}
$('#sponsored-category-header').append('<div class="sponsored-category-logo"></div>');
$('#sponsored-category-header .sponsored-category-logo').append(' <a rel="nofollow" href="'+cat_head_params.logo_url+'" onClick="__gaTracker(\'send\', \'event\', \'Sponsored Category Click Var 1\', \''+cat_head_params.ga_labels[0]+'\', \''+cat_head_params.ga_labels[0]+'\');" target="_blank"><img class="nopin" src="'+cat_head_params.sponsor_logo+'" width="96" height="96" /></a>');
$('#sponsored-category-header').append('<div class="sponsored-category-details"></div>');
$('#sponsored-category-header .sponsored-category-details').append('<h3 class="page-title sponsored-category-title">'+cat_head_params.sponsor+'</h3>');
$('#sponsored-category-header .sponsored-category-details').append(cat_head_params.sponsor_text);
});</script> </div>
This is what I actually get:
<div id="sponsored-category-header" class="page-header sponsored-category-header clear"> <script type="text/javascript">jQuery(document).ready(function($) {
var cat_head_params = {"sponsor":"SEO PowerSuite","sponsor_logo":"https:\/\/www.searchenginejournal.com\/wp-content\/plugins\/abm-sej\/includes\/category-images\/SPS_128.png","sponsor_text":"<div class=\"taxonomy-description\">Dominate Google local search results with ease! Get your copy of SEO PowerSuite and keep <a rel=\"nofollow\" href=\"http:\/\/sejr.nl\/PowerSuite-2016-5\" onClick=\"__gaTracker('send', 'event', 'Sponsored Category Click Var 1', 'Local Search', 'SEO PowerSuite');\" target=\"_blank\">your local SEO strategy<\/a> up to par.<\/div>","logo_url":"http:\/\/sejr.nl\/PowerSuite-2016-5","ga_labels":["Local Search","SEO PowerSuite"]}
$('#sponsored-category-header').append('<div class="sponsored-category-logo"></script>
</div>');
$('#sponsored-category-header .sponsored-category-logo').append(' <a rel="nofollow" href="'+cat_head_params.logo_url+'" onclick="__gaTracker(\'send\', \'event\', \'Sponsored Category Click Var 1\', \''+cat_head_params.ga_labels[0]+'\', \''+cat_head_params.ga_labels[0]+'\');" target="_blank"><img class="nopin" src="'+cat_head_params.sponsor_logo+'" width="96" height="96"></a>');
$('#sponsored-category-header').append('<div class="sponsored-category-details"></div>');
$('#sponsored-category-header .sponsored-category-details').append('<h3 class="page-title sponsored-category-title">'+cat_head_params.sponsor+'</h3>');
$('#sponsored-category-header .sponsored-category-details').append(cat_head_params.sponsor_text);
}); </div>
In case you missed it, the ending script tag has moved up a few lines.
Just to be clear, I am not talking about rendered HTML. I am talking about the actual source code that I get after making the request. Any help on how to resolve this issue will be appreciated.
I know that the function saveHTML is causing the issue because when I echo the whole page through PHP, every tag is in the right place.
First of all, your code should be triggering a good bunch of warnings like these:
Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in
Entity Warning: DOMDocument::loadHTML(): Unexpected end tag :
strong in Entity Warning: DOMDocument::loadHTML(): Tag header
invalid in Entity
This is to expect with on-the-wild HTML (and this page's code is nor particularly bad) but you haven't even mentioned it, what makes me suspect that you might not have error reporting enabled in your development box.
Additionally, the page has huge amounts of JavaScript and DOMDocument is just an HTML parser.
With that, we can get a clear picture of what's happening. Since DOMDocument is not a full-fledged browser it doesn't understand JavaScript code. That means that it detects the <script> tag but it doesn't handle its contents as JavaScript—it merely looks for a closing tag and the first one he finds is this:
$('#sponsored-category-header').append('<div class="sponsored-category-logo"></div>');
^^^^^^
It doesn't know that it's a JavaScript string and should be ignored. Instead, it thinks the wrong tag is being closed so it attempts to fix what's technically invalid HTML and adds the missing </script> tag.
For this precise reason, the <script>...</script> tag set has traditionally been written this way:
<script type="text/javascript"><!--
var foo = '<p>Escaped end tag<\/p>';
//--></script>
... so user agents that are unaware of JavaScript can safely ignore the whole tag (hey, it's nothing but a good old HTML comment). However, nowadays it's almost universally considered bad practice because "all browsers understand JavaScript".
Final note: the DOM extension is probably aware of the <script> tag and knows it isn't allowed to have other tags inside. That explains why inner opening tags are not considered.
Hi I have a question about automating selecting certain content in an HTML. So if we save an webpage as html only, then we'll get HTML codes along with other stylesheets and javascript codes. However, I only want to extract the HTML codes between <div class='post-content' itemprop='articleBody'>and</div> and then create a new HTML file that has the extracted HTML codes. Is there a possible way to do it? Example codes are down below:
<html>
<script src='.....'>
</script>
<style>
...
</style>
<div class='header-outer'>
<div class='header-title'>
<div class='post-content' itemprop='articleBody'>
<p>content we want</p>
</div>
</div></div>
<div class='footer'>
</div>
</html>
While I'm typing, I'm thinking about javascript, which seems to be able to manipulate HTML DOM elements..Is Ruby able to do that? Can I generate a new clean html that only contains content between <div class='post-content' itemprop='articleBody'>and</div> by using javascript or Ruby? However, as for how to write the actual code, I don't have a clue.
So anybody has any idea about it? Thank you so much!
I'm not quite sure what you're asking, but I'll take a crack at it.
Can Ruby modify the DOM on a webpage?
Short answer, no. Browsers don't know how to run Ruby. They do know how to run javascript, so that's what usually used for real-time DOM manipulation.
Can I generate a new clean html
Yes? At the end of the day, HTML is just a specifically formatted string. If you want to download the source from that page and find everything in the <div class='post-content' itemprop='articleBody'> tag, there are a couple of ways to go about that. The best is probably the nokogiri gem, which is a ruby HTML parser. You'll be able to feed it a string (from a file or otherwise) that represents the old page and strip out what you want. Doing that would look something like this:
require 'nokogiri'
page = Nokogiri::HTML(open("https://googleblog.blogspot.com"))
# finds the first child of the <div class="post-content"> element
text = page.css('.post-content')[0].text
I believe that gives you the text you're looking for. More detailed nokogiri instructions can be found here.
You want to use a regular expression. For example:
//The "m" means multi-line
var regEx = /<div class='post-content' itemprop='articleBody'>([\s\S]*?)<\/div>/m;
//The content (you'll put the javascript at the bottom
var bodyCode = document.body.innerHTML;
var match = bodyCode.match( regEx );
//Prints to the console
console.dir( match );
You can see this in action here: https://regex101.com/r/kJ5kW6/1
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a best practice for generating html with javascript
I want to generate large parts of a website with JavaScript.
The straightforward way is to form one large string containing all the HTML:
'<div>'
+ '<span>some text</span>'
+ '<form>'
+ '<input type="text" />'
...
But this gets quite annoying when one has to write a few hundred lines in this style. And the pain when such code has to be changed later on...
Can you think of an easier way?
Create snippets as templates, put them into an invisible <div>:
<div style="display: none">
<div id="template1">
<h2 class="header_identifyingClass">Hello from template</h2>
</div>
<div id="template2">
<span class="content">Blah blah</span>
</div>
</div>
Then find it,
document.getElementById("template1");
fill it's internal values, e.g. find inside elements by XPath or jQuery and fill them e.g. using element.innerHTML = "Hello from new value", and move or copy it to the visible part of DOM.
Create multiple templates and copy it multiple times to generate many.
Don't forget to change the ID for copies to keep it working.
PS: I think I used this approach in the code of JUnitDiff project. But it's buried in XSLT which serves another purpose.
By far the best way to do this is to use some kind of JavaScript templating system. The reason why this is better than hiding HTML with CSS is that if (for example) someone has CSS disabled, they'll be able to see your templates, which is obviously not ideal.
With a templating system, you can put the templates in a <script> tag, meaning that they're totally hidden from everything except JavaScript.
My favourite is the jQuery templating system, mostly because jQuery is so ubiquitous these days. You can get it from here: http://api.jquery.com/category/plugins/templates/
An example (taken from the jQuery docs):
<ul id="movieList"></ul>
<!-- the template is in this script tag -->
<script id="movieTemplate" type="text/x-jquery-tmpl">
<li><b>${Name}</b> (${ReleaseYear})</li>
</script>
<!-- this script will fill out the template with the values you assign -->
<script type="text/javascript">
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];
// Render the template with the movies data and insert
// the rendered HTML under the "movieList" element
$( "#movieTemplate" ).tmpl( movies )
.appendTo( "#movieList" );
</script>
It's a simple example, but you could put all of the HTML you'd like to generate in the <script>, making it much more flexible (use the same HTML snippet for various jobs, just fill out the gaps), or even use many templates to build up a larger HTML snippet.
Use a dialect of JavaScript such as CoffeeScript. It has heredocs:
'''
<div>
<span>some text</span>
<form>
<input type="text" />
'''
If you need to throw in an occasional expression, you can use interpolations:
"""
<title>#{title}</title>
"""
If it's static content that you're just adding to the page on a javascript event, you could consider simply having it in your main HTML page all along, but style with display:none;.
Then it's just a case of changing it's style to make it appear on the page. Much easier.
Even if it's dynamic, you could use this technique: have the shell HTML content there hidden in your page, and populate the dynamic bits before making it visible.
hope that helps.