javascript how to make all strings italic after hyphen? - javascript

Good morning to all
I have a question related to my big commerce products title. here I need the first part of the product's title in bold and after the hyphen or dash the second part need in italic. But problem is that the products title comes with one global variable %%GLOBAL_ProductName%% which I cannot make separated with the span tag. so can you suggest me how I can achieve the rest of strings after hyphen show in Italics with the help of javascript?
For example, check this screenshot https://www.screencast.com/t/fKy0FhByzzl
and here is big commerce website http://rp-staging2.mybigcommerce.com/categories
<li class="%%GLOBAL_AlternateClass%%">
<div class="ProductImage" data-product="%%GLOBAL_ProductId%%">
%%GLOBAL_ProductThumb%%
</div>
<div class="OutOfStockMessage InfoMessage" style="%%GLOBAL_ItemSoldOut%%">
%%SNIPPET_SideAddItemSoldOut%%
</div>
<div class="ProductActionAdd" onclick="location.href='%%GLOBAL_ProductLink%%';">
<p>%%GLOBAL_ProductName%%
</p>
<p><em class="p-price">%%GLOBAL_ProductPrice%% USD</em>
</p>
%%GLOBAL_ProductAddText%%
</div>
</li>
%%GLOBAL_ProductName%%
this variable showing products name please check screenshot and website i have provided link

Using some of the cool es6 features (array destructuring and template literals)
$(".pname").each(function () {
[beforeDash, afterDash] = $(this).text().split(" - ");
$(this).html(`${beforeDash} - <i>${afterDash}</i>`);
});
Looks like:

And if you are using jQuery in your website, you can use something like this:
$( window ).on( "load", function(){
var text = $('.text');
var x = text.text().split('-');
text.html(`${x[0]} - <i>${x[1]}<i>`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
Hello - World
</div>

When ever possible do this kind of split at the server side. Because client side you will manipulate strings after loading the page. So it is not good to do at client side. But anyhow I have written jquery code to fulfill your requirement. I have written in a click event for demo purpose. Please do the logic on onload event.
$("#btn").click(function(){
$(".productName").each(function(){
var title = $(this).text();
var firstSentence = "<b>"+title.substr(0,title.indexOf('-'))+"</b>";
var secondSentence = "<i>"+title.substr(title.indexOf('-')+1)+"</i>";
var finalTitle = firstSentence+ "-" + secondSentence;
$(this).html(finalTitle);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a class="productName"> Sample1 - Product Name1</a><br>
<a class="productName"> Sample2 - Product Name2</a><br>
<input id="btn" type="button" value="Change Format">
</body>
</html>

Check this if it helps...
https://jsfiddle.net/Lz8p11mc/1/
You need to split your product name with '-' and then add these isolated names in separate spans and then you can style these spans as you want. I have written code for simple test case , you can modify it as per your requirement.
<html>
<script>
var productName = 'ABC-XYZ';
var separatedNames = productName.split('-');
var firtsName = separatedNames[0];
var secondname = separatedNames[1];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myTag").innerHTML = '<span>'+firtsName+'</span>-<span class="secondnameCls">'+secondname+'</span>';
}
</script>
<body>
<li class="%%GLOBAL_AlternateClass%%">
<p><a id='myTag'></a></p>
</li>
</body>
</html>

Related

HTML/CSS - How to set text (e.g. 'Quote of the Day') to change automatically on page load/reload?

I am quite new to HTML/CSS. I've got a fairly basic website going in which I have a funny quote under my title. My friend asked me if it changes every time the page loads and that gave me the idea to do something like that. I was wondering if there was any way to manage this in HTML/CSS. I do know some Javascript, so I can also do it on that if needed.
Do I need a list of quotes saved in a file? Can they be pulled from a website/online list? What is the most efficient way to do this?
Thanks
There is a free Quote and Expression API called Forismatic which retrieves a random inspiring quote or expressions. See here for an example quote.
I created an example Codepen of this API using JQuery with AJAX and Bootstrap:
<script>
$(function() {
var quote = $('.quote-text');
getQuote(quote);
$('#getQuote').click(function(event) {
event.preventDefault();
getQuote(quote);
});
});
function getQuote(quote) {
var url = 'http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?';
$.getJSON(url, function(data) {
quote.html(data.quoteText);
});
}
</script>
<div class="jumbotron text-center">
<p class="quote-text"></p>
<button id="getQuote" class="btn">Get Quote</button>
</div>
You can see the codepen here - http://codepen.io/jamesg1/pen/zKORbk
You can use Math.random() to get your randomized index. Math.random() generates a value from 0 (inclusive) to 1 (exclusive).
The onload will be called each time the page is loaded.
<!DOCTYPE html>
<html>
<body onload="randomQuotes()">
<h1>Hello World!</h1>
<p id="quote"></p>
<script>
var quotes = ['hi', 'bye', 'lol', 'hello', 'world']
function randomQuotes() {
var idx = Math.floor(Math.random() * quotes.length)
document.getElementById('quote').innerHTML = quotes[idx]
}
</script>
</body>

How to make contenteditable save permanently and globally?

I am trying to create a page which is very similar to Goodle-Docs, where everybody with access to the page will simply be able to edit the text. However my problem is that I can only get these changes to save locally, how do I make users edit the content-editable text so that the change is visible on all devices?
I am using this tutorial, http://www.developerdrive.com/2012/06/allowing-users-to-edit-text-content-with-html5/ but the changes of the page are only saved locally.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function saveEdits() {
//get the editable element
var editElem = document.getElementById("edit");
//get the edited element content
var userVersion = editElem.innerHTML;
//save the content to local storage
localStorage.userEdits = userVersion;
//write a confirmation to the user
document.getElementById("update").innerHTML="Edits saved!";
}
function checkEdits() {
//find out if the user has previously saved edits
if(localStorage.userEdits!=null)
document.getElementById("edit").innerHTML = localStorage.userEdits;
}
</script>
</head>
<body onload="checkEdits()">
<div id="edit" contenteditable="true">
Here is the element
</div>
<input type="button" value="save my edits" onclick="saveEdits()"/>
<div id="update"> - Edit the text and click to save for next time</div>
</body>
</html>
You are going to need a back-end to sync content between users, and then poll the changes to each user with AJAX.
Personally I'd recommend checking out these javascript libraries and frameworks, as they contain features close to what you're trying to achieve out-of-the-box: ShareJS, Derby and Meteor.
Just like Waiski was saying...
this is pretty old, but I would like to point out...
You are able to do this through localStorage.setItem( //itemname, //contents ),
then to fetch it, localStorage.getItem( //itemname ). for more info check out Mozilla localStorage.... You can do this temorarly but not recommended.
Good Day!
p.s. it may not work here due to not allowing you to setItem under stackoverflow because of a SecurityError, but check it out yourself!
<!DOCTYPE html>
<html>
<head>
<script>
var version = 0;
function saveEdits() {
var editElem = document.getElementById("edit");
version = localStorage.getItem("v");
var versionTxt = document.createTextNode("Version " + localStorage.getItem("v"))
document.body.appendChild(versionTxt);
version++
localStorage.setItem("v", version);
localStorage.setItem("Elm", editElem.innerHTML);
document.getElementById("update").innerHTML="Edits saved!";
}
var editedElem = document.getElementById("edit");
var edits = localStorage.getItem("Elm");
editedElem.innerHTML = edits;
</script>
</head>
<body>
<div id="edit" contenteditable="true">
Edit me
</div>
<button onclick="saveEdits()">save edits</button>
<div id="update"> - Edit the text and click to save for next time</div>
</body>
</html>

Can you use a variable in a url path?

My app has html pages with content in different languages. Id like to use a variable (that is set when selecting a language) in a url like this:
<a href="/language/*variable*/product.html">
edit: I got marked down so to add more info lets says I set this when the page loads
var language = english;
There will be links in the app to change that to other languages ;-)
Let your tag look like this
<a id="link" href="#">Click Me!</a>
Let your variable be called prod.
Add these lines to your javascript wherever you want to update the url.
var hyperl = document.getElementById("link");
hyperl.href = "/language/" + prod + "/product.html";
EDIT:
Use this HTML
<a id="link" href="/language/LANG/product.html">Click Me!</a>
Use this javascript (or similar) to make all links point to the same language (variable name prod):
var links = document.getElementsByTagName("a");
for (i=0; i<links.length; i++) {
var hyperl = links[i];
hyperl.href.replace(LANG, prod);
}
You can use jQuery to dynamically generate the URL.
var string = '/language/'+variable+'product.html';
$(a#language).attr('href', string);
You can use a Javascript function to dynamically replace all href attributes of any <a> tags on the page like so:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<script>
"use strict";
function setLanguage(lang) {
var elements = document.getElementsByTagName('a')
for (var e = 0; e < elements.length; ++e)
{ elements[e].href = elements[e].href.replace(/\?hl=[A-za-z]*/, "?hl=" + lang); }
}
</script>
</head>
<body>
<h1>Search with Google</h1>
<ol>
<li>Search for <b>Python</b></li>
<li>Search for <b>Ruby</b></li>
<li>Search for <b>Javascript</b></li>
</ol>
<br>
<small>
Language:
en
de
</small>
</body>
</html>
In the example above, the ?hl=xxx part of the url is replaced via a regex whenever one of the en or de buttons is pressed.

assigning ID's to body tag using jquery

Help on this guys,
I have here a script that adds an ID on body tag
this is the result I see
<body id="xxx-cat">
with the script I'm using below
<script>
$(document).ready(function(){
// Edit xxx-cat to match desired category link id:
$('body').attr("id","xxx-cat");
if ($('body[id]')) {
var bid = $("body").attr("id");
// Keep the next command on one line
$('div.droplinebar li a[class='+bid+']').addClass('current');
}
})
</script>
How can I make the ID's (1,2,3,4), because I have 4 pages and want it like
<body id="1"> for the home page
<body id="2"> for the about
<body id="3"> for the clients
<body id="4"> for the contact
and by the way this is a tumblr custom page, can't use PHP here
As I understand your question, you can change the scripting, but not the page itself (because it is on Tumblr?)
Try something like:
$(document).ready(function(){
var bodyId = '1'; // Set to 1, 2, 3, 4 etc
$("body").attr('id', bodyId);
$('div.droplinebar li a.'+bodyId).addClass('current');
});
However as mentioned in the comments, you shouldn't just use an number for your ID, consider revising this if possible.
found an answer to My question
$(function() {
var pathname = window.location.pathname;
var getLast = pathname.match(/.*\/(.*)$/)[1];
var truePath = getLast.replace(".php","");
if(truePath === '') {
$('body').attr('id', 'home');
}
else {
$('body').attr('id', truePath);
}
});
results
home = <body id="home">
about = <body id="about">
clients = <body id="clients">
contacts = <body id="contacts">

Generate dynamic hyperlink based on querystring

I wanna generate Hyperlink based on query string .Let me explain it more
Topics clicked rite now:(here I want my hyperlinks)....,....
1.Cat1
2.Cat2
3.Cat3
when i click cat1 it generate querystring: ?Cat=Cat1
when I click on cat2 it will generate querystring ?Cat=Cat2
so based on that I want to create hyperlink whose
text is query string(value)
and url is url-(name and value of that query string)lets say for cat1
if currently url is http://www.google.com/?Cat=Cat1&subcat=subcat1
so text should be cat1(and its url should be www.google.com/?subcat=subcat1)
You may want to take a look at the jquery.query plugin. In particular the get function which returns an array of tokens that you can iterate over.
Something like this should get you started:
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.query.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.each($.query.get(), function(val, prop) {
$('.menu').append($('<a />').attr('href', $.query.empty().set(val, prop).toString()).text(val));
$('.menu').append($('<br />'));
});
});
</script>
</head>
<body>
<div class="menu">
</div>
</body>
</html>
i would say that probably the way to go for this is the following (syntax isnt correct most likely)
I believe this is some regular string manipulation..
var cat1 = "topic1";
var cat2 = "topic2";
var subcat1 = "subtopic1"; etc
url = "http://google.com/?cat=" + cat1 + "&subcat=" + subcat1
<a href=url/>CAT 1 Link<a>
i hope this helps

Categories