I would like to be able to add an item to the list, and view it when I reload the page. I am not sure how to go about doing this. I do not need it stored in a database or anything, I would just like it to be there on screen until I manually delete the list item. Is this possible?
I believe this would be kept on sharepoint, and used with multiple users adding and editing the content, but when I get to that step, I may need additional help with that as well, if that makes any difference to the current question of keeping the LI information.
$("ul").on("click", "li", function(){
$(this).toggleClass("completed");
});
$("ul").on("click", "span", function(event){
$(this).parent().fadeOut(500,function(){
$(this).remove();
});
event.stopPropagation();
});
$("input[type='text']").keypress(function(event){
if(event.which === 13){
var name = $('#name').val();
$('#name').val("");
var number = $('#number').val();
$('#number').val("");
var exception = $('#exception').val();
$('#exception').val("");
var date = $('#date').val();
$('#date').val("");
$("ul").append("<li><span><i class='fa fa-trash'></i></span> " + name + " | " + number + " | " + exception + " | " + date + "</li>")
}
});
$(".fa-plus").click(function(){
$("input[type='text']").fadeToggle();
});
body {
font-family: Roboto;
background: -webkit-linear-gradient(90deg, #2BC0E4 10%, #EAECC6 90%); /* Chrome 10+, Saf5.1+ */
background: -moz-linear-gradient(90deg, #2BC0E4 10%, #EAECC6 90%); /* FF3.6+ */
background: -ms-linear-gradient(90deg, #2BC0E4 10%, #EAECC6 90%); /* IE10 */
background: -o-linear-gradient(90deg, #2BC0E4 10%, #EAECC6 90%); /* Opera 11.10+ */
background: linear-gradient(90deg, #2BC0E4 10%, #EAECC6 90%); /* W3C */
}
ul {
list-style: none;
margin: 0;
padding: 0;
}
h1 {
background: #2980b9;
color: white;
margin: 0;
padding: 10px 20px;
text-transform: uppercase;
font-size: 24px;
font-weight: normal;
}
.fa-plus {
float: right;
}
li {
background: #fff;
height: 40px;
line-height: 40px;
color: #666;
}
li:nth-child(2n){
background: #f7f7f7;
}
span {
background: #e74c3c;
height: 40px;
margin-right: 20px;
text-align: center;
color: white;
width: 0;
display: inline-block;
transition: 0.2s linear;
opacity: 0;
}
li:hover span {
width: 40px;
opacity: 1.0;
}
input {
font-size: 18px;
color: #2980b9;
background-color: #f7f7f7;
width: 100%;
padding: 13px 13px 13px 20px;
box-sizing: border-box;
border: 3px solid rgba(0,0,0,0);
}
input:focus{
background: #fff;
border: 3px solid #2980b9;
outline: none;
}
#container {
width: 360px;
margin: 100px auto;
background: #f7f7f7;
box-shadow: 0 0 3px rgba(0,0,0, 0.1);
}
.completed {
color: gray;
text-decoration: line-through;
}
<!DOCTYPE html>
<html>
<head>
<title>Exceptions</title>
<link rel="stylesheet" type="text/css" href="assets/css/todos.css">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,700,500' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css">
<script type="text/javascript" src="assets/js/lib/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="container">
<h1>2223A Exceptions <i class="fa fa-plus"></i></h1>
<input id="name" type="text" placeholder="Employee Name:">
<input id="number" type="text" placeholder="Employee Number:">
<input id="exception" type="text" placeholder="Employee Exception:">
<input id="date" type="text" placeholder="Employee Date:">
<ul>
<li><span><i class="fa fa-trash"></i></span> #303974 | R. Roberts | SN | 6/25 - 6/27</li>
<li><span><i class="fa fa-trash"></i></span> #303354 | B. Smith | SN | 6/15 & 6/27</li>
<li><span><i class="fa fa-trash"></i></span> #328937 | K. Stull | NO | 6/26</li>
</ul>
</div>
<script type="text/javascript" src="assets/js/todos.js"></script>
</body>
</html>
Well written question.
Change
$("ul").append("<li><span><i class='fa fa-trash'></i></span> " + name + " | " + number + " | " + exception + " | " + date + "</li>")
To
let li = "<li><span><i class='fa fa-trash'></i></span> " + name + " | " + number + " | " + exception + " | " + date + "</li>";
localStorage.setItem('li', localStorage.getItem('li') + li);
$("ul").append(li);
localStorage is an API that allows you to store data in the browser. All I have done here is stored the li as part of a concatenated string of lis. Then place the new li on the page the way you did before.
Now, your next task is the retrieve the lis from localStorage upon page load. So something like this will work:
// assuming document.ready
let lis = localStorage.getItem('li');
$("ul").append(lis);
That should get you very close.
EDIT: I've modified your jsFiddle to accomplish this goal (adding a new item). You can find it here: https://jsfiddle.net/tsbm02hd/
U can indeed use localstorage or you can use JavaScript Cookie manager for this.
Only downside is that the user has some control since he would bve able to clear his browser and therefor his localstorage and/or Cookies...
I still believe for things like this it is best to use an API call and save this data on the server side....
Related
I have a python flask app and I'm wondering how to have the html page to show the selected parameters from dropdown list, text box, multi-selection etc.
A toy example of my current-working setup looks like this:
app.py
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html",
selection1=["1","2"],
selection2=["1","2"],
)
#app.route("/get-values")
def get_values():
dummy = [
["123", "123", "123"],
["456", "456", "456"],
["789", "789", "789"],
]
result = {
'sessions': dummy,
'total_sessions': 3,
'total_pages': 1,
'current_page': 1
}
return jsonify(result)
if __name__ == '__main__':
app.run(debug=True)
The step is basically:
index.html contains the page where user can update parameters to have the table showing different information
when you open the page, it shows the result from default selections
whenever you update any of the field, the result will be updated automatically (done by using $('#selection1-field').on('change', getFirstPageValues);
the update is done by calling /get-values in app.py and sending the new paramters.
What I want to do now is to be able to save (bookmark in browser) the url with updated parameters. Currently it is only saving http://localhost:5000/ which is the home page as well as where the result is shown, but I want it to be able to save url with updated parameters so that next time when I open the bookmarked page, it has the parameters applied already, something like: http://localhost:5000/get-values?c1=v1&c2=v2&c3=v3.
I think I will need to have something like getUrlParam (How to get the value from the GET parameters?) but I'm very new to js and I don't know how to do it. Also probably I need to make changes on the python flask end as well?
Another problem is that since the main url is the index (/) but I'm calling a different endpoint (/get-values) to get data for table, if I were to use something like http://localhost:5000/get-values?c1=v1&c2=v2&c3=v3, then according to the current setup, I'm basically just saving the json output rather than the page with table display of the json output result. Ideally it should be http://localhost:5000/c1=v1&c2=v2&c3=v3 but I don't know how to make this work and I was not able to find any references.
The corresponding index.html is below. You should be able to put it under /templates and make the app work. It has function displayResults(result) which is used to display the table.
<!doctype html>
<html>
<head>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<link rel='stylesheet' href='//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css' />
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css'>
<style type='text/css'>
.CSSTableGenerator {
margin: 50px;
padding: 0px;
width: 95%;
border: 1px solid #000000;
-moz-border-radius-bottomleft: 0px;
-webkit-border-bottom-left-radius: 0px;
border-bottom-left-radius: 0px;
-moz-border-radius-bottomright: 0px;
-webkit-border-bottom-right-radius: 0px;
border-bottom-right-radius: 0px;
-moz-border-radius-topright: 0px;
-webkit-border-top-right-radius: 0px;
border-top-right-radius: 0px;
-moz-border-radius-topleft: 0px;
-webkit-border-top-left-radius: 0px;
border-top-left-radius: 0px;
}
.CSSTableGenerator table {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
.CSSTableGenerator tr:last-child td:last-child {
-moz-border-radius-bottomright: 0px;
-webkit-border-bottom-right-radius: 0px;
border-bottom-right-radius: 0px;
}
.CSSTableGenerator table tr td {
-moz-border-radius-topleft: 0px;
-webkit-border-top-left-radius: 0px;
border-top-left-radius: 0px;
}
.CSSTableGenerator table tr:first-child td:last-child {
-moz-border-radius-topright: 0px;
-webkit-border-top-right-radius: 0px;
border-top-right-radius: 0px;
}
.CSSTableGenerator tr:last-child td:first-child {
-moz-border-radius-bottomleft: 0px;
-webkit-border-bottom-left-radius: 0px;
border-bottom-left-radius: 0px;
}
.CSSTableGenerator tr:hover td {
}
/*.CSSTableGenerator tr:nth-child(odd) {
background-color: #aad4ff
}
.CSSTableGenerator tr:nth-child(even) {
background-color: #ffffff
}*/
.CSSTableGenerator td {
vertical-align: middle;
border: 1px solid #000000;
border-width: 0px 1px 0px 0px;
text-align: left;
padding: 7px;
font-size: 13px;
font-family: Arial;
font-weight: normal;
color: #000000;
}
.CSSTableGenerator tr:last-child td {
border-width: 0px 1px 0px 0px
}
.CSSTableGenerator tr:last-child td:last-child {
border-width: 0px 0px 0px 0px
}
.CSSTableGenerator tr:first-child th {
background: -o-linear-gradient(bottom, #005fbf 5%, #003f7f 100%);
background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #005fbf), color-stop(1, #003f7f) );
background: -moz-linear-gradient( center top, #005fbf 5%, #003f7f 100% );
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#005fbf", endColorstr="#003f7f");
background: -o-linear-gradient(top,#005fbf,003f7f);
background-color: #005fbf;
border: 0px solid #000000;
text-align: center;
border-width: 0px 0px 1px 1px;
font-size: 14px;
font-family: Arial;
font-weight: bold;
color: #ffffff;
}
.CSSTableGenerator tr:first-child td:first-child {
border-width: 0px 1px 1px 0px
}
.CSSTableGenerator tr:first-child td:last-child {
border-width: 0px 0px 1px 1px
}
#radial-center {
/* fallback */
background-color: #2F2727;
background-position: center center;
background-repeat: no-repeat;
/* Safari 4-5, Chrome 1-9 */
/* Can't specify a percentage size? Laaaaaame. */
background: -webkit-gradient(radial, center center, 0, center center, 460, from(#1a82f7), to(#2F2727));
/* Safari 5.1+, Chrome 10+ */
background: -webkit-radial-gradient(circle, #1a82f7, #2F2727);
/* Firefox 3.6+ */
background: -moz-radial-gradient(circle, #1a82f7, #2F2727);
/* IE 10 */
background: -ms-radial-gradient(circle, #1a82f7, #2F2727);
/* Opera couldn't do radial gradients, then at some point they started supporting the -webkit- syntax, how it kinda does but it's kinda broken (doesn't do sizing) */
}
td {
vertical-align: top;
}
.content {
width: 650px;
}
.sidebar {
width: 300px;
}
.leftNavButton {
width: 190px;
line-height: 1;
}
/* Start by setting display:none to make this hidden.
Then we position it in relation to the viewport window
with position:fixed. Width, height, top and left speak
speak for themselves. Background we set to 80% white with
our animation centered, and no-repeating */
/* When the body has the loading class, we turn
the scrollbar off with overflow:hidden */
body.isloading {
overflow: hidden;
}
/* Anytime the body has the loading class, our
modal element will be visible */
body.isloading .mymodal {
display: block;
}
.pace .pace-progress {
background: red;
position: fixed;
z-index: 2000;
top: 0;
left: 0;
height: 5px;
-webkit-transition: width 1s;
-moz-transition: width 1s;
-o-transition: width 1s;
transition: width 1s;
}
.pace-inactive {
display: none;
}
.ignoreDetailsRow {
cursor: pointer
}
.mistagDetailsRow {
cursor: pointer
}
.fixDetailsRow {
cursor: pointer
}
.ignoreSummaryRow {
cursor: pointer
}
.fixSummaryRow {
cursor: pointer
}
.mistagSummaryRow {
cursor: pointer
}
pre {
outline: 1px solid #ccc;
padding: 5px;
margin: 5px;
background-color: #000;
}
.string {
color: white;
}
.number {
color: darkorange;
}
.boolean {
color: blue;
}
.null {
color: magenta;
}
.key {
color: gold;
}
/* shirokov additions */
* {
-webkit-border-radius: 3 !important;
-moz-border-radius: 3 !important;
border-radius: 3 !important;
}
.container {
width: 95%;
}
.bootstrap-select > .dropdown-toggle {
width: 100%;
padding-right: 25px;
}
</style>
<title>Test</title>
</head>
<body>
<div id='homepage-container' class='container body-container' style='width: 1500px;'>
<div id='title-div' class='row' style='margin-bottom: 30px;'>
<h1 class='title' style='text-align: center; margin-top: 30px;'>Test</h1>
</div><!-- title-div -->
<div id='form-div' class='row' style='margin-bottom: 30px;'>
<div class='form-holder'>
<form id='query-form'>
<div class='col-lg-1 col-md-1'></div>
<div class='col-lg-2 col-md-2'>
<label id='date-range'>Date</label>
<div id='reportrange' class='pull-right' style='background: #fff; cursor: pointer; padding: 5px 8px; border: 1px solid #ccc; width: 100%'>
<span id='date-field'></span> <b class='caret'></b>
</div>
</div>
<div class='col-lg-1 col-md-1'>
<label>Selection1</label>
<select class='form-control' id='selection1-field'>
{% for d in selection1 %}
<option value="{{ d[0] }}">{{ d[1] }}</option>
{% endfor %}
</select>
</div>
<div class='col-lg-2 col-md-2'>
<label>Selection2</label>
<select id='selection2-field' class='selectpicker form-control' name='selection2' title='All' multiple data-live-search='true' style='width: 100%;'>
{% for d in selection2 %}
<option value='{{ d }}'> {{ d }}</option>
{% endfor %}
</select>
</div>
<div class='col-lg-2 col-md-2'>
<label>Query Search</label>
<input type="text" class="form-control" id="query-search-field">
</div>
</form>
</div><!-- form-holder -->
</div><!-- form-div -->
<div id='result-div' class='row' style='margin-bottom: 30px;'>
<p class='result-num' id='fetching' style='margin-left: 50px;'></p>
<table border="0" cellpadding="0" width="100%" id='result-table'> </table>
<p class='result-num' style='margin-left: 50px;'></p>
</div><!-- result-div -->
</div><!-- homepage-container -->
<script src='https://code.jquery.com/jquery.js'></script>
<script src='//cdn.jsdelivr.net/momentjs/latest/moment.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
<script src='//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js'></script>
<script type='text/javascript'>
$(function() {
var start = moment().year(2019).month(10).day(1);
var end = moment().year(2019).month(10).day(5);
function cb(start, end) {
$('#reportrange span').html(start.format('MMMM DD, YYYY') + ' - ' + end.format('MMMM DD, YYYY'));
getFirstPageValues();
}
$('#reportrange').daterangepicker({
startDate: start,
endDate: end,
alwaysShowCalendars: true,
opens: 'right',
ranges: {
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}, cb);
cb(start, end);
});
function displayResults(result) {
$('.result-num').empty();
$('#result-table').empty();
if ((result == 'ERROR: memory exceeded') || (result == 'ERROR: no results found for given parameters') || (result == 'ERROR: invalid date range')) {
$('#result-table').append(result);
} else {
var sessions = result['sessions'];
var totalSessions = result['total_sessions'];
var totalPages = result['total_pages'];
var currentPage = result['current_page'];
console.log(sessions[0]);
// setup table
var table = $("<table id=\'result-table\' />").addClass('CSSTableGenerator');
var row1 = $("<tr/>");
row1.append($("<td/>").text("C1"));
row1.append($("<td/>").text("C2"));
row1.append($("<td/>").text("C3"));
table.append(row1);
for (var i=0, len=sessions.length; i<len; i++) {
for (var j=0, len2=sessions[i].length; j<len2; j++) {
var c1 = sessions[i][j][0];
var c2 = sessions[i][j][1];
var c3 = sessions[i][j][2];
row = $("<tr/>").css("border-top", "1px solid #d6d6d6");
row.append($("<td/>").text(c1));
row.append($("<td/>").text(c2));
row.append($("<td/>").text(c3));
table.append(row);
}
}
$('.result-num').append('Total sessions: ' + totalSessions.toString() + '<br/>');
$('.result-num').append('Showing page ' + currentPage.toString() + ' out of ' + totalPages.toString() + '<br/>');
if (currentPage == 1) {
$('.result-num').append('>> Next Page');
} else if (currentPage == totalPages) {
$('.result-num').append('<< Prev Page');
} else {
$('.result-num').append('Prev Page << >> Next Page');
}
$('#result-table').append(table);
var nextPageBtn = document.querySelectorAll('#nextpage-btn');
for (var i = 0; i < nextPageBtn.length; i++) {
nextPageBtn[i].addEventListener('click', function(evt) {
goToNextPage(evt);
});
}
var prevPageBtn = document.querySelectorAll('#prevpage-btn');
for (var i = 0; i < prevPageBtn.length; i++) {
prevPageBtn[i].addEventListener('click', function(evt) {
goToPrevPage(evt);
});
}
}
}
function getFirstPageValues() {
$('.result-num').empty();
$('#result-table').empty();
$('#fetching').append('Fetching results...');
var formInputs = {
'date': $('#date-field').html(),
'selection1': $('#selection1-field').val(),
'selection2': JSON.stringify($('#selection2-field').val()),
'querypattern': $('#query-search-field').val(),
'page_num': 1
};
$.get('/get-values',
formInputs,
displayResults
);
}
$('#selection1-field').on('change', getFirstPageValues);
$('#selection2-field').on('change', getFirstPageValues);
$('#query-search-field').on('change', getFirstPageValues);
function goToNextPage(evt) {
evt.preventDefault();
var formInputs = {
'date': $('#date-field').html(),
'selection1': $('#selection1-field').val(),
'selection2': JSON.stringify($('#selection2-field').val()),
'querypattern': $('#query-search-field').val(),
'page_num': parseInt(document.getElementById('nextpage-btn').dataset.page) + 1
};
$.get('/get-values-ns',
formInputs,
displayResults
);
}
function goToPrevPage(evt) {
evt.preventDefault();
var formInputs = {
'date': $('#date-field').html(),
'selection1': $('#selection1-field').val(),
'selection2': JSON.stringify($('#selection2-field').val()),
'querypattern': $('#query-search-field').val(),
'page_num': parseInt(document.getElementById('prevpage-btn').dataset.page) - 1
};
$.get('/get-values',
formInputs,
displayResults
);
}
</script>
</body>
</html>
What I want to do now is to be able to save (bookmark in browser) the
url with updated parameters. Currently it is only saving
http://localhost:5000/ which is the home page as well as where the
result is shown, but I want it to be able to save url with updated
parameters so that next time when I open the bookmarked page, it has
the parameters applied already, something like:
http://localhost:5000/get-values?c1=v1&c2=v2&c3=v3.
You'll need JavaScript. When you modify the value in the select box, you'll need to update the query string so that when you bookmark it, you're bookmarking the correct url.
Modifying a query string without reloading the page
Then in the /get-values route, you need to use request.args.get('c1'), etc. to get the values.
I'm making a lottery random number generator and have it working, all I want to do is change the background colour of the ball varying on what number range its called between. The second block of code is what I have come up with so far.
For example
o 1-9: White
o 10-19: Blue
o 20-29: Ping,
o 30-39: Green,
o 40-49: Yellow
<!DOCTYPE html>
<head>
<!-- meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>NRONLINE - Buckinghamshire Web Design, Digital Marketing Workshops and Kofax Consultancy</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
body {
background: #444;
font-family: sans-serif;
font-size: 18px;
font-weight: 100;
}
ul {
position: absolute;
padding: 0;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
list-style-type: none;
width: 690px;
height: 100px;
}
ul li {
float: left;
width: 100px;
height: 100px;
border-radius: 50px;
margin-right: 10px;
color: white;
text-align: center;
line-height: 100px;
font-size: 36px;
}
ul li:nth-child(5n) {
margin-right: 40px;
}
.ball-placeholder {
background: #222222;
background: -moz-linear-gradient(-45deg, #222222 0%, black 100%);
background: -webkit-gradient(linear, left top, right bottom, color-stop(0%, #222222), color-stop(100%, black));
background: -webkit-linear-gradient(-45deg, #222222 0%, black 100%);
background: -o-linear-gradient(-45deg, #222222 0%, black 100%);
background: -ms-linear-gradient(-45deg, #222222 0%, black 100%);
background: linear-gradient(135deg, #222222 0%, black 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222222', endColorstr='#000000',GradientType=1 );
}
.next-ball, .play-again {
position: absolute;
right: 0;
left: 0;
margin: auto;
border: 0;
color: white;
}
.next-ball {
bottom: 20px;
width: 100px;
height: 40px;
font-size: 16px;
background: #7ac9ed;
}
.play-again {
display: none;
bottom: 20px;
width: 200px;
height: 80px;
font-size: 24px;
background: #d74d2f;
}
.white-ball {
background: #fff;
color:#101010;
}
.blue-ball {
background: #99ccff;
color:#101010;
}
.pink-ball {
background: #ffccff;
color:#101010;
}
.green-ball {
background: #00cc66;
color:#101010;
}
.yellow-ball {
background: #fac600;
color:#101010;
}
</style>
</head>
<body role="document">
<ul class="ball-placeholders">
<li class="ball-placeholder"></li>
<li class="ball-placeholder"></li>
<li class="ball-placeholder"></li>
<li class="ball-placeholder"></li>
<li class="ball-placeholder"></li>
<li class="ball-placeholder"></li>
</ul>
<ul class="lottery"></ul>
<button class="next-ball">Next Ball</button>
<button class="play-again">Play Again!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var arr = new Array();
$('.next-ball').on('click', function(){
//generate random number between 1 and 50
var random = Math.floor(Math.random()*50 ) + 1;
// array to store css class references
var classList = ["white-ball", "blue-ball", "pink-ball", "green-ball", "yellow-ball"];
console.log(random);
//if index of random number is less than 50
if( arr.indexOf(random) == -1){
//generate random number
arr.push(random);
//add css class to lottery-ball class relevant to array value range
$('.lottery').append('<li class="lottery-ball ' + classList[Math.floor(random/10)] + '">' + random + '</li>');
}
// if the number already exists ignore and generate a new number
else {
console.log(random);
}
console.log(arr);
//if lottery number calls is greater than 5 then switch button classes and send an alert to the user
if ( $('.lottery').children().length > 5 ) {
$('.next-ball').hide();
$('.play-again').show();
alert('Did You Win?');
}
});
//If once the game is finished the user chooses to play again switch button classes
$('.play-again').on('click', function(){
$('.lottery').children().remove();
arr = [];
$('.next-ball').show();
$('.play-again').hide();
});
</script>
</body>
</html>
Your idea should work, but since the only thing that changes is the class of the li it could be more compact. Here I've stored the class names in an array, and used the first digit of the ball number - Math.floor(random/10) to find the right element. Also your indexOf line had a bug - a return of zero from indexOf means the element was found at the start of the array, so check for -1.
var classList = ["white-ball", "blue-ball", "pink-ball", "green-ball", "yellow-ball"];
if( arr.indexOf(random) == -1){
arr.push(random);
$('.lottery').append('<li class="lottery-ball ' + classList[Math.floor(random/10)] + '">' + random + '</li>');
}
Another alternative could be CSS attribute selectors. We could use the 'starts with' selector ^, which will target all elements whose attribute in question... well, starts with a particular string.
Say we give each li representing a ball a data-* attribute equal to its number. Then we can style their backgrounds like so:
li[data-number^=0] {
/*target numbers less than 10
Need to append 0 in front of numbers <10
for this to work*/
background: white;
}
li[data-number^=1] {
/*target numbers in the teens*/
background: blue;
}
li[data-number^=2] {
/*target numbers in the twenties*/
background:pink;
}
/*...and so on...*/
Then the JS is somewhat simplified to:
if (arr.indexOf(random) == -1) {
arr.push(random);
$('.lottery').append('<li class="lottery-ball" data-number="' + (random < 10 ? '0' : '') + random + '">' + random + '</li>';
}
EDIT: here's a link for other types of attribute selectors.
I am trying to add a hover over effect on my boxes but it doesn't seem to show when you add a background color. I have added a border to the a: hover tag and when you hover over any box it does something odd. I was told that it is working, but for some reason its just hidden. The problem seems to be in my onlineBorders() function or css code.
Here is the link: http://codepen.io/duel_drawer8/pen/QNxyNq?editors=0001
CSS:
body {
background-color: #FF7A5A;
}
#rectangles {
margin: 3px;
}
.container {
margin: 0px auto;
width: 700px;
}
.name {
width: 80px;
padding-top: 25px;
font-weight: bold;
color: #00AAA0;
}
.img-responsive {
height: 70px;
}
#rectangles img {
margin-left: -15px;
}
.description {
padding-top: 25px;
color: #FCF4D9;
}
.topHeader {
border: 2px solid black;
margin: 10px;
}
.topOnline #rectangles {
background: #FFB85F;
}
.middleOffline #rectangles {
background: #462066;
}
.bottomClosed #rectangles {
background: #462066;
}
#allTypes {
background:
}
a:hover{
border: 2px solid;
}
Javascript:
function onlineBorders(url, format, status, displayLogo, displayName, infoStreaming) {
$(format).append('<div id="profilePic" class="col-xs-2">' + '<img class="img-responsive" src=' + displayLogo + '>' + '</div><div class="col-xs-3 text"><p class="name">' + displayName + '</p>' + '</div>' + '<div class="description col-xs-7">' + infoStreaming + '</div></div>' + '')
}
So if you are just trying to add a hover to the rectangles all you need to do is replace
a:hover{
border: 2px solid;
}
with
#rectangles:hover{
background-color: white;
border: 2px solid blue;
box-sizing: border-box
}
You can check it out here: http://codepen.io/gogojojo/pen/aZoxYq
Also I would try avoiding using ids when you have more than one of type of whatever. It would make much more sense to add a class rectangles to all of the boxes instead of an id.
You weren't very clear about what is "weird," but I think you just need to add this to your CSS:
a {
display:block;
}
Anchors are inline elements, so you need to make then block or inline-block for the border to display properly.
To clean up the style a little more, you can try:
a {
display:block;
padding:5px;
}
a:hover{
border: 2px solid;
padding:3px;
}
As Joseph mentioned, you have the same ID used for several elements in your HTML, which is not valid markup. An ID must be unique for the page.
My CSS above works by selecting all the anchors to apply the style, but you may consider adding a new CSS class to apply the style with.
<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<body class="w3-container">
<h2>Buttons</h2>
<input type="button" class="w3-btn w3-hover-aqua" value="Input Button">
<button class="w3-btn w3-hover-red">Button Button</button>
<a class="w3-btn w3-hover-blue" href="#">Link Button</a>
<h2>Links </h2>
Hover on the link
</body>
</html>
I have 4 images on the html site just two are visible . Thumbs Up and thumbs down. I have javascript code and i want the user can choose only one of the possibilities. If user click on thumbs up or down it get donker color. But my script lets allow user choose both possibilities.
i want this
Html Code:
<body>
<img id="myImage" onclick="changeImage()" src="../Image/kleindownglow.jpg">
<img id="myImage2" onclick="changeImage2()" src="../Image/kleinupglow.png">
</body>
Script
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("glow")) {
image.src = "../Image/kleindown.jpg";
} else {
image.src = "../Image/kleindownglow.jpg";
}
}
function changeImage2() {
var image2 = document.getElementById('myImage2');
if (image2.src.match("upglow")) {
image2.src = "../Image/kleinup.png";
} else {
image2.src = "../Image/kleinupglow.png";
}
}
Thank you for any help
HTML
<p>
<input type="checkbox" id="test1" />
<label for="test1">Red</label>
</p>
CSS
/* Base for label styling */
[type="checkbox"]:not(:checked),
[type="checkbox"]:checked {
position: absolute;
left: -9999px;
}
[type="checkbox"]:not(:checked) + label,
[type="checkbox"]:checked + label {
position: relative;
padding-left: 25px;
cursor: pointer;
}
/* checkbox aspect */
[type="checkbox"]:not(:checked) + label:before,
[type="checkbox"]:checked + label:before {
content: '';
position: absolute;
left:0; top: 2px;
width: 24px; height: 24px;
border: 1px solid #aaa;
background: #f8f8f8;
border-radius: 3px;
}
[type="checkbox"]:not(:checked) + label:before
{
background-image: url('https://cdn1.iconfinder.com/data/icons/freeapplication/png/24x24/Bad%20mark.png');
}
[type="checkbox"]:checked + label:before
{
background-image: url('https://cdn1.iconfinder.com/data/icons/icojoy/noshadow/standart/gif/24x24/001_18.gif') !important;
}
/* checked mark aspect */
[type="checkbox"]:not(:checked) + label:after,
[type="checkbox"]:checked + label:after {
position: absolute;
top: 0; left: 4px;
font-size: 14px;
color: #09ad7e;
transition: all .2s;
}
/* checked mark aspect changes */
[type="checkbox"]:not(:checked) + label:after {
opacity: 0;
transform: scale(0);
}
[type="checkbox"]:checked + label:after {
opacity: 1;
transform: scale(1);
}
/* disabled checkbox */
[type="checkbox"]:disabled:not(:checked) + label:before,
[type="checkbox"]:disabled:checked + label:before {
box-shadow: none;
border-color: #bbb;
background-color: #ddd;
}
[type="checkbox"]:disabled:checked + label:after {
color: #999;
}
[type="checkbox"]:disabled + label {
color: #aaa;
}
/* accessibility */
[type="checkbox"]:checked:focus + label:before,
[type="checkbox"]:not(:checked):focus + label:before {
border: 1px dotted blue;
}
/* hover style just for information */
label:hover:before {
border: 1px solid #4778d9!important;
}
JQuery
$("input[type='checkbox']").change(function(){
var checkedSt=$(this).prop('checked');
alert(checkedSt ? "Like" : "UnLike");
});
DEMO
Indeterminate added
DEMO
Here's JSBin that solves your issue: http://jsbin.com/fiwadinosemi/1/edit
What it does:
If both are unselected and you press one of them - pressed item is glowed
If one item is glowed and you press it - it just removes glowing effect
If one item is glowes and you press other one - other one is glowed and old one is unglowed
So, this is normal behavior for up/downvote buttons
If you want to make your code work, you would need to add a reference to the opposite image in your code and set that image to the unselected version.
If I were to do this, it would be pure CSS with a sprite and radio buttons.
HTML:
<input type="radio" name="vote1" class="vote" id="down1" value="down" /><label for="down1"></label>
<input type="radio" name="vote1" class="vote" id="up1" value="up" /><label for="up1"></label>
<hr/>
<input type="radio" name="vote1" class="vote" id="down2" value="down" /><label for="down2"></label>
<input type="radio" name="vote1" class="vote" id="up2" value="up" /><label for="up2"></label>
CSS:
.vote { display: none; }
.vote + label {
display: inline-block;
width:55px;
height:65px;
background-image: url(http://i.imgur.com/oRg1EVq.png);
}
.vote[value="up"] + label {
background-position: 55px 66px;
}
.vote[value="up"]:checked + label {
background-position: 55px 0px;
}
.vote[value="down"] + label {
background-position: 0px 66px;
}
.vote[value="down"]:checked + label {
background-position: 0px 0px;
}
Image:
Imgur
Fiddle:
http://jsfiddle.net/coL4LhtL/
First of all I am not very good in designing but with some help I am able to acheive this code
My main issue is that when a user opens a div it becomes the target div, so if I have five divs open at the same time it doesn't matter which I type in because the text gets appended to the last opened div. I can also open an unlimited amount of the same div, which should not happen.
The small issue I have is that I'm unable to close the div and minimize it(much like fb when we click on the chat box it gets minimized).
Fiddle
HTML
<div id="contact">
<header>Users</header>
<main>
<ul>
<li id="Prashant">Prashant</li>
<li id="Katrina">Katrina</li>
<li id="Priyanka">Priyanka</li>
<li id="Kareena">Kareena</li>
<li id="Anushka">Anushka</li>
</ul>
</main>
</div>
<div id="chat"></div>
CSS
* {
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
body{margin:0;padding:0;}
#contact {
height: auto;
background: #ececec;
position:absolute;
right:0;
bottom:0;
width:100px;
}
#contact header {
padding: 10px;
background: #333;
color: #FFF;
}
#contact main {
padding: 10px
}
#chat {
position: fixed;
bottom: 0;
left: 0;
right: 100px;
height: auto;
}
#chat .user {
border: 1px solid #333;
background: #fff;
width: 200px;
height: 100%;
float: left;
margin-right: 5px;
}
.user header {
position: relative;
background: #4b67a8;
border: 1px solid #2e4588;
}
.user header .status {
position: absolute;
top: 36%;
left: 10px;
width: 8px;
height: 8px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
background: green;
}
.user header .header-text {
color: #fff;
font-weight: bold;
padding: 8px;
margin: 0 0 0 15px;
font-size: 12px;
text-shadow: 0 -1px rgba(0, 0, 0, .25);
}
.user header .close {
position: absolute;
right: 5px;
top: 7px;
color: #fff;
}
.message-area {
background: #fff;
height: 120px;
padding: 5px;
color: #333;
overflow: scroll;
}
.user .input-area {
border-top: 1px solid #333;
padding: 3px;
}
.user .input-area input {
padding: 5px;
width: 100%;
font-size: 12px;
border: none;
outline: none;
}
Javascript
var username = 'user201';
$(document).ready(function() {
$('a').click(function(e) {
e.preventDefault();
var targetUser = ($(this).html());
$(document).data('chat.targetUser', targetUser);
var user = '<div class="user open" id="' + targetUser + '"><header><div class="status"></div><div class="header-text">' + targetUser + '</div><div class="close">×</div></header><div class="message-area"></div><div class="input-area"><input type="text" id="input" /></div></div>';
$('#chat').append(user);
});
$('#chat').on('keydown', '#input', function(event) {
if (event.keyCode == 13) {
var targetUser = $(document).data('chat.targetUser');
var txt = $(this).val();
$('#' + targetUser + ' .message-area').append(username + ': ' + txt + '<br/>');
$(this).val('');
}
});
});
I edited div.close and added a div.mini like
<div class="mini" title="MINIMIZE">-</div>
<div class="close" title="CLOSE">×</div>
Css for .mini
.user header .mini {
position: absolute;
right: 25px;
top: 7px;
color: #fff;
cursor:pointer;
}
JS code for them to work
$(document).on("click", "div.close", function(){
$(this).parent().parent().remove();
});
$(document).on("click", "div.mini", function(){
var elem = $(this).parent().parent().children().not("header");
elem.slideToggle();
});
Also added this js code to prevent add the div if it's already opened and make it append to last section of chat
if ($("div#" + targetUser).length > 0) {
$("div#" + targetUser).appendTo("#chat");
return false;
}
FIDDLE
EDIT
Edited div.mini click function for -/+ Minimize/Maximize
$(document).on("click", "div.mini", function(){
var elem = $(this).parent().parent().children().not("header");
elem.slideToggle();
$(this).text($(this).text() == "-" ? "+" : "-");
$(this).attr("title", $(this).attr("title") == "MINIMIZE" ? "MAXIMIZE" : "MINIMIZE");
});
UPDATED FIDDLE
The text you enter will appear in the last opened div because your var targetUser is changed every time you click on one of the users. The best way to solve this I think is to find the parent of the input field and search for the previous .message-area.
Like this:
$('#chat').on('keydown', '#input', function(event) {
if (event.keyCode == 13) {
var txt = $(this).val();
$(this).parent().prev(".message-area").append(username + ': ' + txt + '<br/>');
$(this).val('');
}
});
Working JSFiddle
Here is the fix for your code:
http://jsfiddle.net/afzaal_ahmad_zeeshan/36pcu/14/
I have updated the code in your fiddle, and I have added a fix so that the divs don't open up twice.
I just added a class to the link of the user, to show that this user is now active. Here is the code
if($(this).attr('class') != 'active') {
var targetUser = ($(this).html());
$(document).data('chat.targetUser', targetUser);
var user = '<div class="user open" id="' + targetUser + '"><header><div class="status"></div><div class="header-text">' + targetUser + '</div><div class="close">×</div></header><div class="message-area"></div><div class="input-area"><input type="text" id="input" /></div></div>';
$('#chat').append(user);
}
$(this).attr('class', 'active');
Then the div thing was handled using this code:
if (event.keyCode == 13) {
var txt = $(this).val();
$(this).parent().prev(".message-area").append(username + ': ' + txt + '<br/>');
$(this).val('');
}
This was the fix for your code, now it works.
According to your statement "...Also I am able to open an unlimited amount of the same divs, which should not happen**..." this can be prevented if you know what are the boxes opened
please check the Fiddle
var id = '#Box' + targetUser;
var existent = $('#chat').find(id)[0];
// This will ensure that you can only open one box at each time
if(existent != null){
alert('There is already one chat to user "' + targetUser + '" open');
}
else
{
your code...
}
Also the fix proposed by speetje33 helps you prevent to write always in the last box.
I've added some comments to the code for your better understanding.