Javascript file download with Joomla - javascript

I am coding in Joomla in which I have self synchronized three audio tracks i.e when one of them starts on the web page the other stop and below is the JS code for the same;
<script type="text/javascript">
function _(id) {
return document.getElementById(id);
}
//function Download(url) {
//document.getElementById('my_iframe').src = url;
//};
function audioApp() {
var audio = new Audio();
var audio_folder = "/images/audios/how-to-meditate/relaxation/";
var audio_ext = ".mp3";
var audio_index = 1;
var is_playing = false;
var playingtrack;
var trackbox = _("trackbox");
var tracks = {
"track1": ["Relaxation in the Forest", "relaxation-in-the-forest"],
"track2": ["Relaxation of the Muscles", "relaxation-of-the-muscles"],
"track3": ["Relaxation with the Breath", "relaxation-with-the-breath"]
};
for (var track in tracks) {
var tb = document.createElement("div");
var pb = document.createElement("button");
//var dn = document.createElement("button");
var tn = document.createElement("div");
tb.className = "trackbar";
pb.className = "playbutton";
//dn.className = "download";
tn.className = "trackname";
tn.innerHTML = tracks[track][0];
pb.id = tracks[track][1];
tb.appendChild(pb);
pb.addEventListener("click", switchTrack);
tb.appendChild(tn);
trackbox.appendChild(tb);
audio_index++;
}
audio.addEventListener("ended", function() {
_(playingtrack).style.background = "url(images/icons/play.JPG)";
playingtrack = "";
is_playing = false;
});
function switchTrack(event) {
if (is_playing) {
if (playingtrack != event.target.id) {
is_playing = true;
_(playingtrack).style.background = "url(images/icons/play.JPG)";
event.target.style.background = "url(images/icons/pause.JPG)";
audio.src = audio_folder + event.target.id + audio_ext;
audio.play();
} else {
audio.pause();
is_playing = false;
event.target.style.background = "url(images/icons/play.JPG)";
}
} else {
is_playing = true;
event.target.style.background = "url(images/icons/pause.JPG)";
if (playingtrack != event.target.id) {
audio.src = audio_folder + event.target.id + audio_ext;
}
audio.play();
}
playingtrack = event.target.id;
}
}
window.addEventListener("load", audioApp);
</script>
Below is the Styling;
<style scoped="scoped" type="text/css">
.trackbar {
background: #FFF;
height: 50px;
font-family: "Arial";
}
.trackbar:nth-child(even) {
background: #FFF;
}
.playbutton {
opacity: .8;
display: block;
float: left;
width: 40px;
height: 40px;
margin: 0px 50px 0px 50px;
background: url(images/icons/play.JPG) no-repeat;
border: none;
cursor: pointer;
outline: none;
}
.playbutton:hover {
opacity: 1;
}
.trackname {
float: left;
color: #000;
margin: 12px 400px 0px 14px;
font-size: 20px;
}
And the html code is;
<div id="trackbox"> </div>
Having achieved this I want to place a download icon besides every mp3 which allows me to download the track, I have the link to download the file and it is placed in the media (Content) of Joomla and also I want a icon to be placed which will trigger the download onClick.
Is there a JS script code available with which I can implement the same.

This is what solved the issue;
<input alt="Submit" src="images/icons/download.jpg" type="image" onclick="document.getElementById('anything').click()" />

Related

How to make a reset button appear after certain requirements?

So, i want a reset button to appear on my page when the score of the player reaches 5. But i can't seem to make it appear.
if (Score == 5) {
btnQuestion.disabled = true;
txtQuestionFeedback.innerText = "Correct! \n Congratulations, you've got 5 stars!";
imgScore5.src = "Images/StarOn.gif";
document.getElementById(btnReset).innerHTML = btnReset;
}
Try the following:
1) Insert your button element inside a DIV like this for easier reading
<div id="resetButtonDiv">
<button id="resetButton"></button> <!-- here goes your button config -->
</div>
2) Change the style like this using JS
<script>
function showResetButton() {
document.getElementById("resetButton").style.display = "none";
if (Score == 5) {
// Replace "Score" with your variable or element
document.getElementById("resetButton").style.display = "show";
}
}
showResetButton()
</script>
This was my way to do it:
ScoreBoard = function(sId, sIntoNode = '', fnOnChange = null) {
this.m_sId = sId != '' ? sId : 'scoreboard';
this.m_iScore = 0;
this.m_fnOnChange = fnOnChange;
if(sIntoNode != '') {
let TargetNode = document.getElementById(sIntoNode);
if(TargetNode) {
TargetNode.innerHTML = TargetNode.innerHTML + '<div class="scoreboard-score" id="' + this.m_sId + '">0</div>';
}
}
}
ScoreBoard.prototype.SetScore = function(iNewScore) {
this.m_iScore = iNewScore;
let scoreBoard = document.getElementById(this.m_sId);
if(scoreBoard) {
scoreBoard.innerHTML = this.m_iScore;
}
if(this.m_fnOnChange && typeof this.m_fnOnChange == 'function') {
this.m_fnOnChange(this);
}
}
ScoreBoard.prototype.AddScore = function(iAmount) {
this.SetScore(this.m_iScore + iAmount);
}
ScoreBoard.prototype.Reset = function() {
this.SetScore(0);
}
ScoreBoard.prototype.GetScore = function() {
return this.m_iScore;
}
function OnScoreChange(target) {
let resetBtn = document.getElementById('myScore-reset');
if(resetBtn) {
if(target.GetScore() >= 5) {
resetBtn.style.display = "block";
} else {
resetBtn.style.display = "none";
}
}
}
var myScore = new ScoreBoard('myScore', 'score', OnScoreChange);
var i = 0;
function test() {
myScore.AddScore(1);
i++;
if(i < 20) setTimeout(test, 1000);
}
test();
div#score {
padding: 12px;
background-color: darkgrey;
font-family: Arial;
border-radius: 12px;
box-shadow: 0 0 12px 3px black;
}
div.score-head {
background-color: black;
color: white;
padding: 6px;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
}
div.scoreboard-score {
background-color: #EAEAEA;
padding: 6px;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
}
div#score button {
display: none;
}
<div id="score">
<button onClick="myScore.Reset();" id="myScore-reset">Reset Score</button>
<div class="score-head">Score:</div>
</div>
I've sorted it guys!
Instead, i just used a visibility attribute on the button to hide it on page startup. And then called on that attribute in a Function for HideButton().
```
function ShowResetButton() {
document.getElementById("btnReset").style.visibility = "visible";
}
```
But thank you all for your input! i really appreciate it!
Take it easy,
Happy coding!

JavaScript Todo List - When I click 'edit' button, it doesn't show input to be able to change a todo

I'm building a todo list in vanilla JavaScript as a part of the exercise. I'm trying to get the 'edit' option to function properly. When I click the 'edit' button, the corresponding text input should be enabled, and auto-selected, then the user should be able to press 'enter' to submit changes.
The problem is that I cannot make Edit functional. Two of the other buttons are working well.
I know that there is similar question allready, and I have tried what was in that question, and still cannot get it done. Please help guys.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>To-do List</h1>
</header>
<input type="text" id="addTodoTextInput" onkeyup="todoButtons.addTodo()" placeholder="Add new todo" maxlength="80" autofocus>
<div>
<button onclick="todoButtons.toggleAll()">Toggle All</button>
<button onclick="todoButtons.deleteAll()">Delete All</button>
</div>
<ol>
</ol>
<script src="script.js"></script>
</body>
</html>
css
body {
display: flex;
flex-direction: column;
align-items: center;
background-color: #eee; /* Lightblue */
font-family: tahoma, sans-serif;
}
h1 {
font-weight: 100;
color: brown;
}
ol {
list-style-type: none;
padding-left: 0;
min-width: 30%;
}
li {
padding: 10px;
border-radius: 8px;
background-color: white;
box-shadow: 0 10px 50px black;
margin-top: 10px;
transition: all .3s ease;
overflow: hidden;
}
li:hover {
box-shadow: 0 10px 50px 3px black;
}
li button {
float: right;
}
button {
background-color: #bbb; /* Darkgrey */
font-weight: bold;
border-radius: 5px;
padding: 5px;
transition: all .3s ease;
cursor: pointer;
}
button:hover {
background-color: #d8d2d2; /* Grey */
color: brown;
}
/* Input for adding new todos */
#addTodoTextInput {
width: 30%;
margin-bottom: 20px;
}
js
var todoButtons = {
todos: [],
addTodo: function(e) {
// When Enter is pressed, new todo is made
if (e.keyCode === 13) {
var addTodoTextInput = document.getElementById('addTodoTextInput');
this.todos.push({
todoText: addTodoTextInput.value,
completed: false
});
// Reseting value after user input
addTodoTextInput.value = '';
todoView.displayTodos();
}
},
changeTodo: function(position, newTodoText) {
this.todos[position].todoText = newTodoText;
todoView.displayTodos();
},
deleteTodo: function(position) {
this.todos.splice(position, 1);
todoView.displayTodos();
},
toggleCompleted: function (position) {
var todo = this.todos[position];
todo.completed = !todo.completed;
todoView.displayTodos();
},
toggleAll: function() {
var totalTodos = this.todos.length;
var completedTodos = 0;
// Checks for a number of completed todos
this.todos.forEach(function(todo) {
if (todo.completed === true) {
completedTodos++;
}
});
this.todos.forEach(function(todo) {
// If all todos are true, they will be changed to false
if (completedTodos === totalTodos) {
todo.completed = false;
}
// Otherwise, they will be changed to true
else {
todo.completed = true;
}
});
todoView.displayTodos();
},
deleteAll: function() {
this.todos.splice(0, this.todos.length);
todoView.displayTodos();
}
};
// Function for displaying todos on the webpage
var todoView = {
displayTodos: function() {
var todosUl = document.querySelector('ol');
todosUl.innerHTML = '';
// Creating list element for every new todo
for (var i = 0; i < todoButtons.todos.length; i++) {
var todoLi = document.createElement('li');
var todoLiText = document.createElement('input');
todoLiText.type = "text";
todoLiText.disabled = true;
todoLiText.id = 'textInput';
var todoTextWithCompletion = todoButtons.todos[i].todoText;
if (todoButtons.todos[i].completed === true) {
todoLi.style.textDecoration = "line-through";
todoLi.style.opacity = "0.4";
todoLi.textContent = todoButtons.todoText + ' ';
}
else {
todoLi.textContent = todoButtons.todoText + ' ';
}
todoLi.id = i;
todoLiText.value = todoTextWithCompletion;
todoLi.appendChild(this.createDeleteButton());
todoLi.appendChild(this.createToggleButton());
todoLi.appendChild(this.createEditButton());
todoLi.appendChild(todoLiText);
todosUl.appendChild(todoLi);
};
},
// Method for creating Delete button for each todo
createDeleteButton: function() {
var deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.className = 'deleteButton';
return deleteButton;
},
// Method for creating Toggle button for each todo
createToggleButton: function() {
var toggleButton = document.createElement('button');
toggleButton.textContent = 'Toggle';
toggleButton.className = 'toggleButton';
return toggleButton;
},
// Method for creating Edit button for each todo
createEditButton: function() {
var editButton = document.createElement('button');
editButton.textContent = 'Edit';
editButton.className = 'editButton';
return editButton;
},
// Event listeners gor the Delete, Edit and Toggle buttons
setUpEventListeners: function() {
var todosUl = document.querySelector('ol');
todosUl.addEventListener('click', function(event) {
var position = event.target.parentNode.id;
var elementClicked = event.target.className;
if (elementClicked === 'deleteButton') {
// Path to the ID of each created todo
todoButtons.deleteTodo(parseInt(position));
}
});
todosUl.addEventListener('click', function(event) {
var position = event.target.parentNode.id;
var elementClicked = event.target.className;
if (elementClicked === 'toggleButton') {
todoButtons.toggleCompleted(parseInt(position));
}
});
todosUl.addEventListener('click', function(event) {
var position = event.target.parentNode.id;
var elementClicked = event.target.className;
if (elementClicked === 'edit') {
var input = document.getElementById(position).childNodes[0];
input.disabled = false;
input.className = "activeTextInput";
input.focus();
input.select();
input.addEventListener('keyup', function(event) {
if(event.keyCode === 13) {
var textInput = input.value;
input.disabled = true;
input.classList.remove("activeTextInput");
todoButtons.changeTodo(position, textInput);
};
});
};
});
}
};
// Starting event listeners when the app starts
todoView.setUpEventListeners();
So, I looked at the code. The first problem is the condition:
if (elementClicked === 'edit') {
It should be:
if (elementClicked === 'editButton') {
The second problem was:
if (elementClicked === 'edit') {
var input = document.getElementById(position).childNodes[0]; //this line
input.disabled = false;
input.className = "activeTextInput";
It should be var input = document.getElementById(position).querySelector('input'); to get the correct element.
https://jsfiddle.net/nh9j6yw3/1/
Reason for "undefined" :
on line todoLi.textContent = todoButtons.todoText + ' ';
todoButtons.todoText is undefined.

Get localStorage value on page load

I've searched the internet but I can't seem to find anything that works for me.
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Heating System Control</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
strLED1 = "";
strLED2 = "";
strText1 = "";
strText2 = "";
var LED1_state = 0;
var LED2_state = 0;
function GetArduinoIO()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null)
{
// XML file received - contains analog values, switch values and LED states
document.getElementById("input1").innerHTML =
this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
document.getElementById("input2").innerHTML =
this.responseXML.getElementsByTagName('analog')[1].childNodes[0].nodeValue;
// LED 1
if (this.responseXML.getElementsByTagName('LED')[0].childNodes[0].nodeValue === "on") {
document.getElementById("LED1").innerHTML = "ON";
document.getElementById("LED1").style.backgroundColor = "green";
document.getElementById("LED1").style.color = "white";
LED1_state = 1;
}
else {
document.getElementById("LED1").innerHTML = "OFF";
document.getElementById("LED1").style.backgroundColor = "red";
document.getElementById("LED1").style.color = "white";
LED1_state = 0;
}
// LED 2
if (this.responseXML.getElementsByTagName('LED')[1].childNodes[0].nodeValue === "on") {
document.getElementById("LED2").innerHTML = "ON";
document.getElementById("LED2").style.backgroundColor = "green";
document.getElementById("LED2").style.color = "white";
LED2_state = 1;
}
else {
document.getElementById("LED2").innerHTML = "OFF";
document.getElementById("LED2").style.backgroundColor = "red";
document.getElementById("LED2").style.color = "white";
LED2_state = 0;
}
}
}
}
}
// send HTTP GET request with LEDs to switch on/off if any
request.open("GET", "ajax_inputs" + strLED1 + strLED2 + nocache, true);
request.send(null);
setTimeout('GetArduinoIO()', 1000);
strLED1 = "";
strLED2 = "";
}
function GetButton1()
{
if (LED1_state === 1)
{
LED1_state = 0;
strLED1 = "&LED1=0";
}
else
{
LED1_state = 1;
strLED1 = "&LED1=1";
}
}
function GetButton2()
{
if (LED2_state === 1)
{
LED2_state = 0;
strLED2 = "&LED2=0";
}
else
{
LED2_state = 1;
strLED2 = "&LED2=1";
}
}
function SendText1()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
strText2 = "&txt2=" + document.getElementById("txt_form1").form_text1.value + "&end2=end";
request.open("GET", "ajax_inputs" + strText2 + nocache, true);
request.send(null);
}
function SendText2()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
strText1 = "&txt1=" + document.getElementById("txt_form2").form_text2.value + "&end1=end";
request.open("GET", "ajax_inputs" + strText1 + nocache, true);
request.send(null);
}
function clsTxt1()
{
setTimeout(
function clearTxt()
{
document.getElementById("txt_form1").form_text1.value = "";
}, 500)
}
function clsTxt2()
{
setTimeout(
function clearTxt()
{
document.getElementById("txt_form2").form_text2.value = "";
}, 500)
}
function Threshold1()
{
var thr1 = document.getElementById("txt_form1").form_text1.value;
document.getElementById("thresh1").innerHTML = thr1;
}
function Threshold2()
{
var thr2 = document.getElementById("txt_form2").form_text2.value;
document.getElementById("thresh2").innerHTML = thr2;
}
</script>
<style>
.IO_box
{
float: left;
margin: 0 20px 20px 0;
border: 1px solid black;
padding: 0 5px 0 5px;
width: 100px;
height: 196px;
text-align: center;
}
h1
{
font-family: Helvetica;
font-size: 120%;
color: blue;
margin: 5px 0 10px 0;
text-align: center;
}
h2
{
font-family: Helvetica;
font-size: 85%;
color: black;
margin: 10px 0 5px 0;
text-align: center;
}
p, form
{
font-family: Helvetica;
font-size: 80%;
color: #252525;
text-align: center;
}
button
{
font-family: Helvetica;
font-size: 80%;
max-width: 100px;
width: 90px;
height: 25px;
margin: 0 auto;
text-align: center;
border: none;
}
input
{
font-family: Helvetica;
font-size: 80%;
max-width: 100px;
width: 90px;
height: 25px;
margin: 0 auto;
text-align: center;
border: none;
}
.small_text
{
font-family: Helvetica;
font-size: 70%;
color: #737373;
text-align: center;
}
textarea
{
resize: none;
max-width: 90px;
margin-bottom: 1px;
text-align: center;
}
</style>
</head>
<body onload="GetArduinoIO(); Threshold1()">
<h1>Heating System Control</h1>
<div class="IO_box">
<h2>Room One</h2>
<p>Temp1 is: <span id="input1">...</span></p>
<button type="button" id="LED1" onclick="GetButton1()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
<form id="txt_form1" name="frmText">
<textarea name="form_text1" rows="1" cols="10"></textarea>
</form>
<input type="submit" value="Set Temp" onclick="SendText1(); clsTxt1(); Threshold1();" style ="background-color:#5F9EA0" />
<p>Threshold: <span id="thresh1">...</span></p>
</div>
<div class="IO_box">
<h2>Room Two</h2>
<p>Temp2 is: <span id="input2">...</span></p>
<button type="button" id="LED2" onclick="GetButton2()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
<form id="txt_form2" name="frmText">
<textarea name="form_text2" rows="1" cols="10"></textarea>
</form>
<input type="submit" value="Set Temp" onclick="SendText2(); clsTxt2(); Threshold2();" style ="background-color:#5F9EA0" />
<p>Threshold: <span id="thresh2">...</span></p>
</div>
</body>
</html>
So my question is, How can I keep the value inserted in the text area even after I reload the page (from the "Threshold1()" function)? I found a few examples with "localStorage" and JQuery, but I have no idea how to call the saved value when I reload the page.
Any help would be appreciated.
Thanks in advance,
Stefan.
Local Storage Explained
The localStorage object likes to store strings, so how would one store large objects, let's say some complex data structure? - Simple, JavaScript has a neat function built in, look up JSON.stringify(object). So all you would need to do is something like below to store some complex object is something like the code I've provided below. Then to retrieve an object from the localStorage you'll want to use JSON.parse(object);.
To look into localStorage, I strongly suggest you take a look at the likes of MDN and if you want to look into the JSON.parse and JSON.stringify functions, you can also find them both here:
JSON.parse() link
JSON.stringify() link
// vanilla js version of $(document).ready(function(){/*code here*/});
window.ready = function(fnc) {
if (typeof fnc != "function") {
return console.error("You need to pass a function as a param.");
}
try { // try time out for some old IE bugs
setTimeout(function () {
document.addEventListener("DOMContentLoaded", fnc());
}, 10)
} catch (e) {
try { // sometimes timeout won't work
document.addEventListener("DOMContentLoaded", fnc());
} catch (ex) {
console.log(ex);
}
}
};
// shorter than $(document).ready();
ready(function() {
var object = {
name: "Jack",
age: 30,
location: "U.S.A.",
get_pay: function() {
console.log("test");
}
},
test;
console.log(object);
var obj_string = JSON.stringify(object);
// run a test
var run_test = function() {
// output the stored object
test = localStorage.getItem("test");
console.log(test);
// to make js turn it into an object again
test = JSON.parse(localStorage.getItem("test"));
console.log(test);
};
// demo of trying to store an actual object
try {
localStorage.setItem("test", object);
run_test();
} catch (e) {
console.log(e);
}
// demo of trying to store the string
try {
localStorage.setItem("test", obj_string);
run_test();
} catch (e) {
console.log(e);
}
});
You can use this JSFiddle : http://jsfiddle.net/xpvt214o/45115/
here we are using Cookie concept and jquery.cookie.js to accomplish what you are trying to do.
to properly check the fiddle you need to press "Run" every time, you can open the same fiddle in 2 tabs write something in the first fiddle then just press run in the 2nd fiddle tab the value should automatically update, here the
$(function(){}); replicates your pageload
My question isn't exactly answered, but I completely avoided storing info on a device. Now I'm just reading the value straight from the arduino and it works. But thanks to everyone that provided some help.

Get increment value from input area in a for-loop

I have done this working fiddle:
HTML
<div id="container">
<div id="input_container">
<label for="increment_t">Set t-increment value (default 0.1):</label>
<input id="increment_t" type="number" min="0" max="1" step="0.1" value="0.1" />
</div>
<br />
<div id="generator_container">
<a id="downloadlink" download="outfile.txt">Download</a>
<button id="create_link">Export output</button>
</div>
</div>
CSS
#container {
position: absolute;
display: block;
left: 0;
top: 0;
padding: 10px 10px; /* (top-bottom) (left-right) */
z-index: 1;
}
#input_container {
display: block;
float: left;
margin-bottom: 10px;
}
#increment_t {
max-width: 50px;
}
#generator_container {
display: block;
float: right;
}
#downloadlink {
display: none;
margin-right: 10px;
}
#create_link {
float: right;
}
JavaScript
(function () {
var t_values;
var t_values_list = [];
for ( var t=0; t<=1; t+=0.1 ){
t_values = t.toFixed(1);
t_values_list.push(t_values);
}
var textFile = null;
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create_link = document.getElementById('create_link');
create_link.addEventListener('click', function () {
alert(t_values_list);
var link = document.getElementById('downloadlink');
link.href = makeTextFile(t_values_list.join('\n'));
link.style.display = 'inline-block';
}, false);
})();
but I want to set the increment value for the "t" variable (i.e. 0.1, in the for-loop) taking it from the input area. I tried in this way:
JavaScript
(function () {
var t_values;
var t_values_list = [];
alert(document.getElementById("increment_t").value); // test to get the t value, to use it in the following loop for
for ( var t=0, increment_t=document.getElementById("increment_t").value; t<=1; t+=increment_t ){
t_values = t.toFixed(1);
t_values_list.push(t_values);
}
var textFile = null;
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create_link = document.getElementById('create_link');
create_link.addEventListener('click', function () {
alert(t_values_list);
var link = document.getElementById('downloadlink');
link.href = makeTextFile(t_values_list.join('\n'));
link.style.display = 'inline-block';
}, false);
})();
but It doesn't work. Thanks for your help
If you getting numbers from somewhere else in javascript...always parse them. parseInt(..., 10) or in your example: parseFloat

highlighting each email in input tag

So, what I am going to do with the input tag is to insert as many as email address inside it.
<input type="text" name="email-tags"/>
To make it more user-friendly, I want to highlight each-email which is typed inside it with blue color, it looks similar like a tag in SO question which also has x button to delete the tag.
Can anybody please help me how to do this with javascript?
Thanks in advance.
This block of code actually does what you need. It's pretty advanced. I hope it suits your needs. document.getElementById("test").value contains the email addresses in an array in this example.
function setInputEmailToExtendedInput()
{
var inputs = document.querySelectorAll("input[data-type='email']");
Array.prototype.slice.call(inputs).forEach(function(element){
var node = new emailInput();
if (element.id)
{
node.container.id = element.id;
}
if (element.className)
{
node.container.className = element.className;
}
element.parentElement.replaceChild(node.container, element);
});
}
function emailInput() {
this.container = document.createElement("div");
this.container.input = document.createElement("input");
this.container.input.type = "text";
this.container.style.overflowY = "auto";
this.container.input.className = "email_input";
this.container.appendChild(this.container.input);
this.container.input.addEventListener("keydown", checkKeyUpOnEmailInputDisable(this), false);
this.evaluateTag = evaluateEmailFunction;
this.deleteTag = deleteEmailFunction;
this.container.input.addEventListener("paste", emailEvaluateOnChange(this), false);
Object.defineProperty(this, "value", {
value: [],
enumerable: false
});
Object.defineProperty(this, "placeholder", {
get: function() {
this.container.input.placeholder;
},
set: function(value) {
this.container.input.placeholder = value;
},
enumerable: false
});
}
function emailEvaluateOnChange(obj, e) {
return function(e) {
obj.evaluateTag(e.target.value);
}
}
function checkKeyUpOnEmailInputDisable(obj, e) {
return function(e) {
if (e.keyCode == 13 || e.keyCode == 32) //either enter or space
{
obj.evaluateTag(e.target.value);
return false;
} else if (e.keyCode == 8) //backspace
{
if (e.target.value.length == 0 && obj.value.length > 0) //length of the input is zero.
{
//delete tag.
obj.deleteTag();
return true;
}
} else if (e.keyCode == 27) //escape
{
//hide the input helper and blur the input.
e.target.blur();
e.preventDefault();
return false;
}
};
}
function deleteEmailFunction(tag) {
if (!tag) {
//delete the last tag
var tag = this.value.length - 1;
}
this.container.removeChild(this.container.querySelectorAll(".email_element")[tag]);
this.value.splice(tag, 1);
if (this.value.length > 0) {
var marginNode = parseInt(getComputedStyle(this.container.children[0]).getPropertyValue("margin-right"));
var width = parseInt(this.container.children[0].offsetLeft) * 2; //default padding
for (var i = 0; i < this.value.length; ++i) {
//calculate the width of all tags.
width += parseInt(this.container.children[i].offsetWidth) + marginNode;
}
this.container.input.style.width = (this.container.offsetWidth - width) - 20 + "px";
} else {
this.container.input.style.width = "100%";
}
this.container.input.focus();
}
function createEmail(value) {
var node = document.createElement("span");
node.className = "email_element";
node.innerHTML = value;
return node;
}
function evaluateEmailFunction(tagValue) {
if (tagValue.match(/[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/ig)) {
//email is valid add
var node = createEmail(tagValue.trim());
this.container.insertBefore(node, this.container.input);
this.value.push(tagValue);
var marginNode = parseInt(getComputedStyle(node).getPropertyValue("margin-right"));
var width = parseInt(this.container.children[0].offsetLeft) * 2; //default padding
for (var i = 0; i < this.value.length; ++i) {
//calculate the width of all tags.
width += parseInt(this.container.children[i].offsetWidth) + marginNode;
}
//set the width of the tag input accordingly.
this.container.input.style.width = (this.container.offsetWidth - width) - 20 + "px";
this.container.input.value = "";
this.container.input.focus();
}
}
RegExp.escape = function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
window.addEventListener("load", function(){setInputEmailToExtendedInput()}, false);
div.email_builder {
width: 500px;
height: 36px;
background-color: #ffffff;
border: 1px solid #777777;
box-sizing: border-box;
}
input.email_input {
padding: 8px 8px 8px 8px;
border: 0px solid transparent;
width: 100%;
box-sizing: border-box;
font-size: 11pt;
}
span.email_element {
display: inline-block;
padding: 6px 2px 6px 2px;
margin-right: 4px;
color: #0059B3;
font-size: 10pt;
white-space: nowrap;
cursor: pointer;
box-sizing: border-box;
}
span.email_element > span.email_remove_button {
color: #000000;
font-size: 10pt;
white-space: nowrap;
cursor: pointer;
padding-left: 12px;
font-size: 14px;
font-weight: bold;
}
span.email_element > span.email_remove_button:hover {
color: #660000;
font-size: 10pt;
white-space: nowrap;
cursor: pointer;
padding-left: 12px;
font-size: 14px;
font-weight: bold;
}
<input type="text" class="email_builder" id="test" data-type="email" />
how about this:
<from id="form" action="">
<span id="emailInput">
<input type="text" name="email-tags"/>
</span>
<span id="test"></span>
</form>
function isValidEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$(function(){
$('input').keydown(function(event){
$input = $(this);
$emailInput = $("#emailInput");
$("#test").html(event.which);
switch(event.which){
//stop for "," ";" and " "
case 188:
case 186:
case 32:
currentEmail = $.trim($input.val());
if(isValidEmail(currentEmail)){
$address = $("<span>");
$address.addClass("emailAddress");
$address.text(currentEmail);
$close=$('<span>');
$close.addClass("close").text("x");
$address.append($close);
$input.val("");
$input.before($address);
}
}
});
$("#emailInput").on("click",".close",function(){
$(this).parent().remove();
});
});
see here:
http://fiddle.jshell.net/wryjde3z/

Categories