dynamically setting variables in html5 body? - javascript

Hi i am trying to dynamically set some of the contents of an html5 body with var strings defined in a JS.
below is what i have written so far and it doesnt seem to display the value specified.
<link href="src/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="src/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="src/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<body>
<script>
var name = "John Smith";
</script>
<div data-role="page" id="page">
<div data-role="header">
<button></button>
<h1>New Claim</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li> <p><h3>Your Name: <var>name</var></h3></p></li>
</ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
i am trying to insert John Smith inside the "Your Name: text.
Thanks

You will have to use JavaScript to "print" the contents of a variable, to the HTML-source. Here's an example:
<div id="test"></div>
document.getElementById('test').innerHTML = 'This goes into the element!';
But since you're using jQuery, you could do this as well:
$('#test').text('This goes into the element!');

You should either give the VAR-Tag itself or it's wrapping LI-Tag an unique ID.
In HTML
<li>
<p>
<h3>Your Name: <var id="name">name</var></h3>
</p>
</li>
JavaScript
var name = "John Smith";
$("#name").text(name);
And by the way:
You shouldn't nest a Heading inside of a Paragraph, this doesn't make any sense.
Paragraphs are INLINE while Headings are BLOCKELEMENTS.
Check out this FIDDLE

You probably want something like below. Have global JS variables assigned, reference them with a VAR html5 tag, use JS at the end of body (or after DOM load) to substitute the keys in the VAR tags with the values held in the global VARS object.
<script>
VARS = {};
VARS.name = "John Smith";
VARS.age = 45;
</script>
...
Name : <var>name</var><br/>
Age : <var>age</var>
...
<script>
// run once at end of body
var all = document.getElementsByTagName("var");
for(var i=0; i<all.length; i++) {
var elm = all[i];
var key = elm.innerHTML;
if(VARS[key] != null)
elm.innerHTML = VARS[key];
else
elm.innerHTML = "";
}
</script>

The tag isn't supposed to be used this way
Try this:
<link href="src/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="src/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="src/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<body>
<script>
var name = "John Smith";
$(document).ready(function() {
$("#name").text(name);
});
</script>
<div data-role="page" id="page">
<div data-role="header">
<button></button>
<h1>New Claim</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li> <p><h3>Your Name: <span id="name"></span></h3></p></li>
</ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
Edit: just to clarify one thing. The tag isn't supposed to be used to hold the place to the value of a variable. It's correct semantic meaning is more to represent a mathematical variable or a programming variable when you are showing some code on your page. If I'm wrong here, please someone correct me.

try this
$(document).ready(function() {
$("h3").text("Your name : John Smith");
});
Add some classes on your divs, to easuly select the good tags

Related

responsivevoice - I have to read the text inside the html element to the sound robot

responsivevoice .org
I couldn't do the text voice over service as I wanted.
There is no detailed explanation on the website.
I don't want to use < textarea > The example I want to use. I don't want to choose a robot. It should only speak Turkish Male. How should I do this?
<div id = "text-read"> one two tree four five </div>
<button onclick="responsiveVoice.speak('text-read');" type="button" value="Play">Play</button>
I want it to read the contents with the button.
Thank you for your interest
resources:
https://responsivevoice.org/api
https://responsivevoice.org/text-to-speech-sdk/text-to-speech-play-button
https://responsivevoice.org/text-to-speech-sdk/text-to-speech-widget
<script src="https://code.responsivevoice.org/responsivevoice.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
<!-- Turkish Man Or Women Voice -->
var element = document.getElementById('#erkekoku');
var text = element.innerText || element.textContent;
element.innerHTML = erkekoku;
var element = document.getElementById('#erkekoku');
var text = element.innerText;
function manspeak(obj) {
responsiveVoice.speak($('#erkekoku').text(), 'Turkish Male');
};
</script>
<div id="erkekoku">Bu metni seslendirdim.</div>
<button class="btn btn-primary" onclick="manspeak('article')">Play</button>
<html>
<head>
<script src="https://code.responsivevoice.org/responsivevoice.js"></script>
<script>
ResponsiveVoice.setDefaultVoice("Australian Male");
</script>
</head>
<body>
<button onclick="speakText();" type="button">Play</button>
<script>
function speakText() {
var text = document.getElementById('text-read').innerText;
responsiveVoice.speak(text, 'Australian Male');
}
</script>
<div id="text-read">
<h1> Heading1. </h1>
<h2> Heading2. </h2>
<ul>
<li> List
<li> One,
<li> Two,
<li> Three,
<li> Four.
</ul>
<p> Paragrah. </p>
</div>
The first parameter of the speak function represents the text to be spoken, the second one defines the voice:
responsiveVoice.speak('bir, i̇ki, üç', 'Turkish Male');
If you want to get the text that is inside some HTML element, you have to query it first, then get its text content and finally pass that to the function:
var element = document.getElementById('text-read');
var text = element.innerText;
responsiveVoice.speak(text, 'Turkish Male');

Copy HTML from element, replace text with jQuery, then append to element

I am trying to create portlets on my website which are generated when a user inputs a number and clicks a button.
I have the HTML in a script tag (that way it's invisible). I am able to clone the HTML contents of the script tag and append it to the necessary element without issue. My problem is, I cannot seem to modify the text inside the template before appending it.
This is a super simplified version of what I'd like to do. I'm just trying to get parts of it working properly before building it up more.
Here is the script tag with the template:
var p = $("#tpl_dashboard_portlet").html();
var h = document.createElement('div');
$(h).html(p);
$(h).find('div.m-portlet').data('s', s);
$(h).find('[data-key="number"]').val(s);
$(h).find('[data-key="name"]').val("TEST");
console.log(h);
console.log($(h).html());
console.log(s);
$("div.m-content").append($(h).html());
<script id="tpl_dashboard_portlet" type="text/html">
<!--begin::Portlet-->
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<!--begin::Form-->
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
<!--end::Portlet-->
</script>
I'm not sure what I'm doing wrong here. I've tried using .each as well with no luck. Both leave the value of the span tags empty.
(I've removed some of the script, but the variable s does have a value on it)
You have two issues here. Firstly, every time you call $(h) you're creating a new jQuery object from the original template HTML. As such any and all previous changes you made are lost. You need to create the jQuery object from the template HTML once, then make all changes to that object.
Secondly, the span elements you select by data-key attribute do not have value properties to change, you instead need to set their text(). Try this:
var s = 'foo';
var p = $("#tpl_dashboard_portlet").html();
var $h = $('<div />');
$h.html(p);
$h.find('div.m-portlet').data('s', s);
$h.find('[data-key="number"]').text(s);
$h.find('[data-key="name"]').text("TEST");
$("div.m-content").append($h.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="tpl_dashboard_portlet" type="text/html">
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
</script>
<div class="m-content"></div>
In my case only this is working:
var template = $('template').clone(true, true); // Copies all data and events
var $h = $('<div />');
$h.html(template);
$h.find('.input-name').attr('value', "your value here"); // Note: .val("your value here") is not working
$('.list').prepend($h.html());

Passing variable to function on another page

I am working on a website and am planning on having it so that certain links will have a value set, this will change what container is displayed when the page loads. How would I have it so the link passes a value that would be used for the onload functions?
Here is a mockup of my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lunch</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="script.js"></script>
</head>
<body onload="navBar(); dateChange(); tabulate(0);">
<nav>
<ul>
<li>Appitizers</li>
<li>Breakfast</li>
<li>Lunch</li>
<li>Dinner</li>
<li>Dessert</li>
<li>Ten-Course Dinner</li>
<li>Send in your Recipes!</li>
</ul>
</nav>
<div class="main">
<div class="box">
<ul>
<li><a onclick="tabulate(this.id);" id="1">Chicken Clubhouse Sandwiches</a></li>
<li><a onclick="tabulate(this.id);" id="2">Smokey Tomato Soup</a></li>
</ul>
</div>
<div id="0" class="recipe" style="display: block;">
<div class="tabs">
<a class="tab"> </a>
</div>
<div class="page">
<p>The recipes you'll find here are ones you can use to impress guests at your next get together</p>
</div>
</div> <!--recipe card end-->
<div class="recipe" id="1">
<h1>Chicken Clubhouse Sandwiches</h1>
</div> <!--recipe card end-->
<div class="recipe" id="2">
<h1>Smokey Tomato Soup</h1>
</div> <!--recipe card end-->
</div>
</body>
</html>
And here is my tabulate function:
function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}
else{
this.style.display="none";
}
});
}
You would need to make use of the URL's GET parameters:
lunch.html?item=2
In conjunction with passing the variable into the JavaScript function:
// Set up an object for GET parameter
var $_GET = {};
// Find and extract the various GET parameters
if(document.location.toString().indexOf('?') !== -1) {
var query = document.location.toString().replace(/^.*?\?/, '').replace(/#.*$/, '').split('&');
for(var i=0, l=query.length; i<l; i++) {
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
// Target a specific get parameter, given the GET parameter name
var tabNum = $_GET['item']; // Comes through as '2' in this example
// Pass the parameter into the function
function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}
else{
this.style.display="none";
}
});
}
See this post and this post for further reference.
Hope this helps! :)
I haven't tested this, but you should be able to get by with passing a GET variable via PHP into tabulate(), in a way like this:
function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}
else{
this.style.display="none";
}
});
}
window.addEventListener('DOMContentLoaded', function(evt) {
var id = <?php echo htmlspecialchars($_GET['id'], ENT_COMPAT, 'utf8'); ?>;
tabulate(id);
});

How to replace text inside IDless <span> with javascript?

I have some text inside <span></span> tags and I want to change that text to something else when page is loaded.
So lets say default text is 'Story' (outputted by some CMS system and I can't edit it). So when page is loaded, .js detects that 'Story' word and replaces it with 'View This Story'.
Is that possible somehow?
Cheers
Update: I did search before asking and none of those methods I found works. Like I said the text is outputted by CMS and it gives wrong title, the title itself cannot be edited via CMS because it is used for other terms and tagging which is correct, so I was looking for js workaround to rename it on page load.
And span has no ID and I cannot give it any ID, because like I said it works as designed by CMS.
<div class="views-row views-row-1 views-row-odd views-row-first active">
<div class="views-field views-field-name">
<span class="field-content">Story</span>
</div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="views-field views-field-name">
<span class="field-content">Second Story</span>
</div>
</div>
As you can see spans do not have IDs, but repeating classes only.
UPDATED as per OP request
You can replace any text within spans. You could even use regular expressions to make it more flexible, but let's leave this for now:
Native Javascript
var lookupSpanAndReplace = function(textFrom, textTo) {
var spans = document.getElementsByTagName('span');
for (i=0; i<spans.length; i++)
if (spans[i].innerHTML.indexOf(textFrom) >= 0)
spans[i].innerHTML = mySpan.innerHTML.replace(textFrom, textTo);
}
lookupSpanAndReplace("Story", "My New Text");
jQuery
var lookupSpanAndReplace = function(textFrom, textTo) {
$('span:contains(' + textFrom + ')').each(function(index, element) {
$(element).text($(element).text().replace(textFrom, textTo));
});
}
lookupSpanAndReplace("Story", "My New Text");
Try
$('#spanID').text("View This Story");
or if you want to replace a part of text
$('#spanID').text(function () {
return this.innerHTML.replace('Story', 'View This Story');
});
Give you span an ID and then run text([your new text]) on that node:
HTML
<span id="mySpan">Story</span>
jQuery
$('#mySpan').text("View This Story");
JSFiddle with jQuery
Or you can do it without jQuery:
document.getElementById("mySpan").innerHTML = "View This Story";
JSFiddle with plain 'ol Javascript
<script>
function changeSpan(){
var spans = document.getElementsByTagName ("span");
for (i = 0; i < spams.length; i++){
spans[i].innerHTML = textThatYouWant ();
}
}
</script>
<head onload="changeSpan()" >
<tile> ... </title>
</head>
<body>
...
</body>
Use the following to solve the issue.
HTML code:
<html>
<head>
<script>
function replace_text_span()
{
for(i=0;i<document.getElementsByTagName('span').length;i++)
{
document.getElementsByTagName('span')[i].innerHTML=document.getElementsByTagName('span')[i].innerHTML.replace("Story","View This Story");
}
}
</script>
<style>
</style>
</head>
<body onload="replace_text_span()">
<div class="views-row views-row-1 views-row-odd views-row-first active">
<div class="views-field views-field-name">
<span class="field-content">Story</span>
</div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="views-field views-field-name">
<span class="field-content">Second Story</span>
</div>
</div>
</body>
</html>

Append a div after another div with javascript

Is there any predefined method in javascript that can append div after a div?
For example:
<div class="uploader">
<div class="file-metas">
<div class="file-name">status<span class="file-size">1kb</span></div>
<p class="state state-success">Success</p>
</div>
</div>
Now I want to insert another div with class name 'remove' after 'uploader' div.
Yeah it is possible using pure javascript
You can use insertBefore method to do so by accessing parent node of target element.
document.getElementsByClassName("uploader").parentNode
Take a look
Try this Demo
var node = document.querySelector(".uploader"),
ele = document.createElement("div");
ele.className = "remove";
ele.innerHTML = "some text";
node.parentNode.insertBefore(ele, node.nextSibling);
Vanilla JS: Supported with all the browsers:
Visualization of position names
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
code
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
More info here
function appendAfter(divToAppend, siblingBefore) {
if(siblingBefore.nextSibling) {
siblingBefore.parentNode.insertBefore(divToAppend, siblingBefore.nextSibling);
} else {
siblingBefore.parentNode.appendChild(divToAppend);
}
}
The following example demonstrates what you are trying to achieve using plain JavaScript:
<html>
<head>
<script>
function addNewDiv() {
var newDiv = document.createElement('div');
var label = document.createTextNode(" - new div - ");
var elements = document.getElementsByClassName('uploader');
var uploaderDiv = elements[0];
newDiv.appendChild(label);
elements[0].insertBefore(newDiv, uploaderDiv.children[0]);
}
</script>
</head>
<body>
<div class="uploader">
<div class="file-metas">
<div class="file-name">status<span class="file-size">1kb</span>
</div>
<p class="state state-success">Success</p>
</div>
</div>
<input type="button" onClick="addNewDiv()" value="Add new Div" />
</body>
</html>

Categories