Menu navigation not working with jquery datepicker - javascript

I have database generated menu with child menu items in my MVC4 web application which was working fine until I didn't implemented Jquery datepicker. As soon as I included datetimepicker.js and jqueryui bundle, my menu stopped expending. I had tried to change order of scripts and style but no success. I am fairly new to css so I am not be able to figure out whats going wrong here.
Here is my _Layout.cshtml:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="~/Images/Company-logo/logo.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jqueryui")
#Styles.Render("~/Content/themes/base/css","~/Content/themes/base", "~/Content/css")
<script src="~/Scripts/DatePickerReady.js"></script>
<link href="~/Content/indexView.css" rel="stylesheet" />
</head>
<body>
<header>
<div>
<img src="~/Images/Company-logo/header_bar.png" style="width:100%"/>
</div>
<div class="content-wrapper">
<div class="float-right">
#Html.Partial("Menu")
</div>
</div>
</header>
<div id="body">
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
</div>
<footer>
</footer>
<script src="#Url.Content("~/Scripts/dbGeneratedMenu.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/dbGeneratedMenu.css")" rel="stylesheet" type="text/css" />
#RenderSection("scripts", required: false)
</body>
<script type="text/javascript">
$m = jQuery.noConflict();
$m(document).ready(function () {
$m('.menu').dbGeneratedMenu();
});
</script>
</html>
Following is my css for menu:
.menu, .menu ul
{
margin: 0;
padding: 0;
list-style-type: none;
position: relative;
line-height: 2.5em;
}
.menu a
{
text-decoration: none;
}
.menu > li
{
margin-left: 15px;
}
.menu > li:first
{
margin-left:0px!important;
}
.menu > li > a
{
padding: 0px 10px;
margin: 0;
width: 100%;
text-decoration: none;
color: #005D7C;
font-weight: bold;
}
div.box
{
position: absolute;
z-index: -1;
background-color: #75CDD2;
left: 0;
top: 0;
border-radius: 4px 4px 0px 0px;
-moz-border-radius: 4px 4px 0px 0px;
-webkit-border-radius: 4px 4px 0px 0px;
}
li.pull-down
{
padding-right:6px;
}
li.pull-down > a
{
background-image: url(/Images/menu/darrow.png);
background-position: 96% 75%;
background-repeat: no-repeat;
padding-right: 20px;
}
li.right-menu > a
{
background-image: url(/Images/menu/rarrow.png);
background-position: 97% 45%;
background-repeat: no-repeat;
}
.menu a.selected
{
background-color: #75CDD2;
border-radius: 0px 4px 4px 4px;
-moz-border-radius: 0px 4px 4px 4px;
-webkit-border-radius: 0px 4px 4px 4px;
}
.menu li
{
float: left;
position: relative;
}
.menu ul
{
position: absolute;
display: none;
width: 200px;
top: 2.5em; /*padding-right: 10px;*/
background-color: #B8C402; /*-moz-opacity: .50; filter: alpha(opacity=50); opacity: .50;*/
border-radius: 0px 4px 4px 4px;
-moz-border-radius: 0px 4px 4px 4px;
-webkit-border-radius: 0px 4px 4px 4px;
}
.menu li ul a
{
width: 180px;
height: auto;
float: left;
color: #FFFFFF;
padding: 0 10px;
}
.menu li ul li
{
padding: 0;
margin: 0;
}
.menu ul ul
{
top: auto;
}
.menu li ul ul
{
left: 198px; /*margin: 0px 0 0 10px;*/
}
.menu-item-selected > a
{
background-color: #000000;
-moz-opacity: .50;
filter: alpha(opacity=50);
opacity: .50;
font-weight: bold;
}
a:hover {
background-color: #B8C402;
color: #FFFFFF !important;
}
.menu-item-selected > a:hover
{
background-color: #000000;
color: #FFFFFF !important;
}
This is JQuery fiddle for database generated menu:
(function ($) {
$.fn.extend({
dbGeneratedMenu: function () {
return this.each(function () {
//add class .drop-down to all of the menus having drop-down items
var menu = $(this);
var timeoutInterval;
if (!menu.hasClass('menu')) menu.addClass('menu');
$("> li", menu).each(function () {
if ($(this).find("ul:first").length > 0)
$(this).addClass('pull-down');
});
$("> li ul li ul", menu).each(function () {
$(this).parent().addClass('right-menu');
});
$("li", menu).mouseenter(function () {
var isTopLevel = false;
//if its top level then add animation
isTopLevel = $(this).parent().attr('class') === 'menu';
if (isTopLevel) {
clearTimeout(timeoutInterval);
var w = $(this).outerWidth();
// if ($(this).hasClass('pull-down')) w += 10;
var h = $(this).outerHeight();
var box = $('<div/>').addClass('box');
$('> li', menu).removeClass('selected');
$('>li div.box', menu).remove();
$('>li ul', menu).css('display', 'none').slideUp(0);
$(this).prepend(box);
$(this).addClass('selected');
box.stop(true, false).animate({ width: w, height: h }, 100, function () {
if ($(this).parent().find('ul:first').length == 0) {
timeoutInterval = setTimeout(function () {
box.stop(true, false).animate({ height: '+=5' }, 300, function () {
box.parent().find('ul:first').css('display', 'block').css('top', box.height()).stop(true, false).slideDown(100);
});
}, 10);
}
else {
timeoutInterval = setTimeout(function () {
box.stop(true, false).animate({ height: '+=0' }, 0, function () {
box.parent().find('ul:first').css('display', 'block').css('top', box.height()).stop(true, false).slideDown(100);
});
}, 10);
}
});
}
else {
$(this).find('ul:first').css('display','block').stop(true, false).slideDown(100);
}
}).mouseleave(function () {
isTopLevel = $(this).parent().attr('class') === 'menu';
if (isTopLevel) {
$(this).parent().find('div.box').remove();
}
$(this).find('ul').slideUp(100, function () {
$(this).css('display', 'none');
});
});
$('> li > ul li a', menu).hover(function () {
$(this).parent().addClass('menu-item-selected');
}, function () {
$(this).parent().removeClass('menu-item-selected');
});
});
}
});
})(jQuery);
Partial view for date:
#model DateTime?
#{
var value = "";
if (Model.HasValue) {
value = String.Format("{0:d}", Model.Value.ToString("dd-MM-yyyy"));
}
}
#Html.TextBox("", value, new { #class = "datefield", type = "date" })
model:
public class LEAVE_REQUEST
{
[Display(Name = "Id"), Required, DatabaseGenerated(DatabaseGeneratedOption.None)]
public long ALLOTMENT_REQUEST_ID { get; set; }
[Display(Name = "Request date"), Required]
public Nullable<System.DateTime> REQUEST_DATE { get; set; }
[Display(Name = "Leave start date"), Required(ErrorMessage="Leave start date not entered")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd-mm-yyyy}")]
public Nullable<System.DateTime> LEAVE_START_DATE { get; set; }
}
View where I am implementing datetimepicker
#model TESTAPP.Models.LEAVE_REQUEST
#{
ViewBag.Title = "Create";
}
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<fieldset>
<legend>LEAVE_REQUEST</legend>
<div class="editor-label">
#Html.LabelFor(model => model.LEAVE_START_DATE)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LEAVE_START_DATE)
#Html.ValidationMessageFor(model => model.LEAVE_START_DATE, "*")
</div>
#Html.ValidationSummary(false)
<p>
<input type="submit" value="Submit" class="submitButton"/>
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I really appreciate any help from you guys. Thanks

I finally solved my problem. I think something is conflicting in JQuery bundle with js file I'd used for menu navigation. I used jquery-1.8.2.min.js only instead of rendering entire bundle. and now its working as expected. However, I am still not be able to find what conflict with what :(

Related

Change placeholder on link click in html

With below code I'm trying to change the placeholder for select element on link click. But no changes are seen as of now. Also I'm trying to figure out how to show div when click on gear icon. Currently it works when click on div but not for icon present in it.
<!doctype html>
<html lang="en">
<head>
<!-- Dropdown - > https://stackoverflow.com/questions/43579748/how-to-achieve-autocomplete-feature-over-html-drop-down-or-select-element -->
<!-- focus in-out event > https://stackoverflow.com/questions/57284729/onclick-change-width-of-dropdown-using-javascript/57284975#57284975 -->
<title>jQuery UI Autocomplete - Default functionality</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet" />
<style>
.dropbtn {
background-color: #3498DB;
color: white;
padding: 8px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 8px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 8px 8px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
</style>
<script>
$(function() {
$('select')
.select2({
placeholder: 'Search Command...',
width: '200',
multiple: false,
data: [{
id: '',
text: ''
}, {
id: 'rrrrrrr',
text: 'testing1'
}, {
id: 'testing 1,2,3',
text: 'testing 1,2,3gffffff'
}],
tokenSeparators: ['|']
})
$('.select2-container').click(function() {
$(this).css('width','500px');
});
$('.select2-container').focusout(function() {
$(this).css('width','200px');
});
$('#changeCommand').click(function() {
$('select').css('placeholder','Search Command...');
});
$('#changePref').click(function() {
$('select').css('placeholder','Search Preferences...');
});
$('#changeCD').click(function() {
$('select').css('placeholder','Search Customer Default...');
});
});
</script>
<script>
<!-- https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown -->
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
</head>
<body>
<select></select> <div class="dropdown"><button class="dropbtn" onclick="myFunction()" style="border-radius: 3px;border: none;color: black; background-color: white;"><span>⚙</span></button></div>
<div id="myDropdown" class="dropdown-content">
<a id="changeCommand">Commands</a>
<a id="changePref">Preferences</a>
<a id="changeCD">Customer Default</a>
</div>
</body>
</html>
You can try the following way:
$(function() {
$('select')
.select2({
placeholder: 'Search Command...',
allowClear: true,
width: '200',
multiple: false,
data: [{
id: '',
text: ''
}, {
id: 'rrrrrrr',
text: 'testing1'
}, {
id: 'testing 1,2,3',
text: 'testing 1,2,3gffffff'
}],
tokenSeparators: ['|']
})
.on('select2:open', function() {
$('.select2-container').css('width','600px');
})
.on("select2:close", function () {
$('.select2-container').css('width','200px');
});
$('#changeCommand').click(function() {
$('.select2-selection__placeholder').text('Search Command...');
});
$('#changePref').click(function() {
$('.select2-selection__placeholder').text('Search Preferences...');
});
$('#changeCD').click(function() {
$('.select2-selection__placeholder').text('Search Customer Default...');
});
});
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
var dropdowns = document.getElementById("myDropdown");
if (event.target.classList.contains('dropbtn')) {
dropdowns.classList.toggle("show");
}
else if (!event.target.classList.contains("dropbtn") && dropdowns.classList.contains("show")){
dropdowns.classList.toggle("show");
}
}
.dropbtn {
background-color: #3498DB;
color: white;
padding: 8px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 8px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 8px 8px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet" />
<select></select>
<div class="dropdown"><button class="dropbtn" style="border-radius: 3px;border: none;color: black; background-color: white;">⚙</button></div>
<div id="myDropdown" class="dropdown-content">
<a id="changeCommand">Commands</a>
<a id="changePref">Preferences</a>
<a id="changeCD">Customer Default</a>
</div>
Just remove remove the subscription on the window.onclick event.
The onclick event on you button will be fired when child elements are clicked. Your current logic will show and directly hide the dropdown

How to convert toggle function to module pattern in javascript?

I'm a new javascript, i have heard that declaring global variables it's pretty much bad idea in javascript, we have to less or avoid as much as we can.
I have found page https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals and i saw module pattern it seems a good way to go.
So, i've been practicing about toggle function my first code it works fine
function toggle() {
var mainTopics = document.querySelector("#maintopics"); // target the li
mainTopics.addEventListener("click", function (e) { // passed "e" to get the event
e.preventDefault(); // prevent anchor to navigate
mainTopics.classList.toggle("show"); // changed to toggle for the
// the purpose of this demo
});
}
toggle();
body {
margin: 0;
}
li, a{
text-decoration: none;
list-style-type: none;
text-decoration-line: none;
color: black;
}
/*main-menu*/
#mainmenu {
position: relative;
}
#mainmenu ul {
margin: 0;
padding: 0;
}
#mainmenu li {
display: inline-block;
}
#mainmenu a {
display: block;
width: 100px;
padding: 10px;
border: 1px solid;
text-align: center;
}
/*sub-topics*/
#subtopics {
position: absolute;
display: none;
margin-top: 10px;
width: 100%;
left: 0;
}
#maintopics.show #subtopics {
display: block;
}
#subtopics ul {
margin: 0;
padding: 0;
}
#subtopics li {
display: block;
}
#subTopics a {
text-align: left;
}
/*columns*/
#column1, #column2, #column3 {
position: relative;
float: left;
left: 125px;
margin: 0px 5px 0px 0px;
}
/*hover underline*/
#mainmenu li:hover {
text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="index2.css" />
</head>
<body>
<div id="mainmenu">
<ul>
<li>Logo</li>
<li>Home</li>
<li id="maintopics">Topics
<div id="subtopics">
<div id="column1" class="columns">
<ul>
<li>example1</li>
<li>example2</li>
<li>example3</li>
</ul>
</div>
</div>
</li>
</ul>
</div>
<script src="index2.js"></script>
</body>
</html>
I changed code javascript to module pattern.However it didn't work, im not sure if my code is wrong or there is some important rule that i don't know.
If anyone would like to give me some advices i will appreciate it thank you very much.
var toggle = (function() {
var mainTopics = document.getElementById("maintopics");
mainTopics.addEventListener("click", function(e) {
e.preventDefault();
mainTopics.classList.toggle("show");
});
return {
toggle()
}
})();
Hi, everyone i suddenly found the solution for my case. i just need to specific the function that i want to return to object again for example in my case return toggle function it would be toggle: toggle()
var toggle = (function () {
var mainTopics = document.getElementById("maintopics");
mainTopics.addEventListener("click", function (e) {
e.preventDefault();
mainTopics.classList.toggle("show");
});
return {
toggle: toggle()
}
})();

Saving To-Do list data to local storage with HTML

So if I want to save all the To-Do items in Local storage and retrieve when I restart the computer or refresh the page all the items come up on the page in their original order.?
//check of spec
$("ol").on("click", "li", function(){
$(this).toggleClass("completed");
});
//click on X to delete To-DO
$("ol").on("click", "span", function(event){
$(this).parent().fadeOut(500,function(){
$(this).remove();
});
event.stopPropagation();
});
$("input[type='text'").keypress(function(event){
if(event.which === 13) {
//grabbing the text typed
var todoText = $(this).val();
$(this).val("");
//create a new LI and add to UL
$("ol").append("<li><span><i class='fa fa-trash'></i></span> " + todoText +"</li>")
}
});
$(".fa-plus").click(function(){
$("input[type='text'").fadeToggle();
});
h1 {
background: #2980b9;
color: white;
margin: 0;
padding: 10px 15px;
text-transform: uppercase;
font-size: 24px;
font-weight: normal;
}
iframe {
float: left;
}
ol {
/* THE BULLET POINTS
list-style: none;
*/
margin: 0;
padding: 0;
font-size: 18px;
}
body {
background-color: rgb(13, 168, 108);
}
li {
background: #fff;
height: 30px;
line-height: 30px;
color: #666;
}
li:nth-child(2n){
background: #d3d3d3;
}
span {
height: 30px;
width: 0px;
margin-right: 20px;
text-align: center;
color:white;
display: inline-block;
transition: 0.2s linear;
opacity:0;
background: #e74c3c
}
li:hover span {
width: 30px;
opacity: 1.0;
}
input {
font-size: 18px;
width: 100%;
padding: 13px 13px 13px 20px;
box-sizing: border-box;
border: 3px solid rgba(0,0,0,0);
color: #2980b9;
background-color: #e4e4e4;
}
input:focus {
background: white;
border: 3px solid green;
/*OUTLINE OF INPUT BOX
outlin: none; */
}
.fa-plus {
float: right;
}
#container {
width: 360px;
margin: 60px auto;
background: #d3d3d3;
box-shadow: 0 0 3px rgba(0,0,0,0.1);
}
.completed {
color: red;
text-decoration: line-through;
}
<!DOCTYPE html>
<html>
<head>
<title>ToDo List</title>
<link rel="stylesheet" type="text/css" href="utd.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
</head>
<body>
<iframe src="http://free.timeanddate.com/clock/i5zr5d5i/n1991/szw110/szh110/hoc09f/hbw0/hfc09f/cf100/hnce1ead6/fas30/fdi66/mqc000/mql15/mqw4/mqd98/mhc000/mhl15/mhw4/mhd98/mmc000/mml10/mmw1/mmd98/hhc00f/hhs2/hmcf00/hms2/hsv0" frameborder="0" width="110" height="110"></iframe>
<div id="container">
<h1>To-do List <i class="fa fa-plus"></i></h1>
<form id="task-list">
<input type="text" placeholder="Add a To-Do" id="task">
</form>
<ol id="sortable">
<li><span><i class="fa fa-trash"></i></span> EXAMPLE</li>
</ol>
</div>
<script type="text/javascript" src="Utd.js"></script>
</body>
</html>
Happy Holidays!
Your coding wishes are granted. This is a gift, to you, and you will have to be a good person and post better examples and remember that people are not here to write code for you.
There was a LOT of stuff lacking from your example.
Add items to a list
Update local storage when items are added to a list
Allow list to be sorted
Update local storage when list is updated
Allow task items to be marked completed
Update local storage when items are completed
Allow task items to be deleted
Update local storage when tasks are deleted
Load locally stored tasks
I think that covers everything you wanted this script to do. Is it becoming more clear now?
Working Example: https://jsfiddle.net/Twisty/ae6oLr47/12/
HTML
<iframe src="https://free.timeanddate.com/clock/i5zr5d5i/n1991/szw110/szh110/hoc09f/hbw0/hfc09f/cf100/hnce1ead6/fas30/fdi66/mqc000/mql15/mqw4/mqd98/mhc000/mhl15/mhw4/mhd98/mmc000/mml10/mmw1/mmd98/hhc00f/hhs2/hmcf00/hms2/hsv0" frameborder="0" width="110"
height="110"></iframe>
<div id="container">
<h1>To-do List <i class="fa fa-plus"></i></h1>
<form id="task-list">
<input type="text" placeholder="Add a To-Do" id="task">
<button type="submit"></button>
</form>
<ol id="sortable">
<li id="task-EXAMPLE"><span><i class="fa fa-trash"></i></span>
<label>EXAMPLE</label>
</li>
</ol>
</div>
The first time this loads, there will be no storage, so we can read an examples from the HTML. As you will see, once you make an update, this will no longer be the case.
Q: Why the <button>?
A: <form> likes to have a submit button. It does not need it, yet having it will help a lot in ways I do not want to go into for this question.
JavaScript
$(function() {
$("#sortable").on("click", function(event) {
console.log(event.target);
var $thatItem = $(event.target).parents("li");
switch (event.target.nodeName) {
case "SPAN":
case "I":
$thatItem.fadeOut(500, function() {
$thatItem.remove();
$("#sortable").sortable("refresh");
});
break;
case "LABEL":
$thatItem.toggleClass("completed");
break;
}
setTimeout(function() {
updateLocalStorage($("#sortable"));
}, 500);
event.stopPropagation();
});
$("#task-list").submit(function(event) {
event.preventDefault();
// Grabbing the text typed
var todoText = $("#task").val();
addListItem($("#sortable"), todoText, false);
// Clear the text field
$("#task").val("");
updateLocalStorage($("#sortable"));
});
$(".fa-plus").click(function() {
$("#task-list").fadeToggle();
});
$("#sortable").sortable({
update: function(e, ui) {
updateLocalStorage($(this));
}
}).disableSelection();
function addListItem($t, s, c) {
//create a new LI
var $li = $("<li>", {
id: "task-" + s.replace(" ", "_")
});
if (c) {
$li.addClass("completed");
}
var $wrap = $("<span>").appendTo($li);
$wrap.append($("<i>", {
class: "fa fa-trash"
}));
$li.append($("<label>").html(s));
$li.appendTo($t);
$t.sortable("refresh");
}
function updateLocalStorage($list) {
var tasks = {};
$list.find("li").each(function(ind, elem) {
var task = $(elem).text().trim();
var completed = $(elem).hasClass("completed");
tasks[task] = completed;
if (typeof(Storage) !== "undefined") {
localStorage.setItem("tasks", JSON.stringify(tasks));
}
});
}
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
if (localStorage.getItem("tasks") !== "undefined") {
var localTasks = JSON.parse(localStorage.getItem("tasks"));
// Grab stored tasks
$("#sortable").find("li").remove();
$.each(localTasks, function(task, status) {
addListItem($("#sortable"), task, status);
});
}
} else {
// Sorry! No Web Storage support..
}
});
You might see that there is very little of your original code left in here. There was just a lot of places to improve the code. I will discuss a bit briefly.
Click Events
Since we're basically listening for click events on the same parent, but want to do different things when specific elements are clicked, that are going to be dynamically created, we can make use of the event.target from the click event. If it's the span or the i that's clicked, we do one thing, if it's the label, another.
The setTimeout is just a way to create a delay in the operations from switch to updating. Otherwise the update will execute almost on top of the switch and will not see the changes to the list, this record no changes.
Submit Event
When you hit Enter or Return you're essentially submitting the form. Part of the reason to add a submit button. Instead of catching the keypress and trying to prevent this, why not just use the submit event to our advantage. This method will help on mobile browsers and such.
Sortable Update Event
When the list is sorted, and updated, we need to update that order in the local storage. Now is the time to do that.
Functions
I think these are pretty clear. You have an operation you will repeat many times, write a function.
Get Item
The last bit of code will load when the page is all ready. It will check for localStorage and check if there are tasks stored within. It will then populate the list with them.
Q: What's with the JSON.stringify()?
A: Yes, you can store stuff locally... only as String. This creates a string version of our object for storage.
Comment if you have other questions.
//check of spec
$("ol").on("click", "li", function(){
$(this).toggleClass("completed");
});
//click on X to delete To-DO
$("ol").on("click", "span", function(event){
$(this).parent().fadeOut(500,function(){
$(this).remove();
});
event.stopPropagation();
});
$("input[type='text'").keypress(function(event){
if(event.which === 13) {
//grabbing the text typed
var todoText = $(this).val();
$(this).val("");
//create a new LI and add to UL
$("ol").append("<li><span><i class='fa fa-trash'></i></span> " + todoText +"</li>")
}
});
$(".fa-plus").click(function(){
$("input[type='text'").fadeToggle();
});
h1 {
background: #2980b9;
color: white;
margin: 0;
padding: 10px 15px;
text-transform: uppercase;
font-size: 24px;
font-weight: normal;
}
iframe {
float: left;
}
ol {
/* THE BULLET POINTS
list-style: none;
*/
margin: 0;
padding: 0;
font-size: 18px;
}
body {
background-color: rgb(13, 168, 108);
}
li {
background: #fff;
height: 30px;
line-height: 30px;
color: #666;
}
li:nth-child(2n){
background: #d3d3d3;
}
span {
height: 30px;
width: 0px;
margin-right: 20px;
text-align: center;
color:white;
display: inline-block;
transition: 0.2s linear;
opacity:0;
background: #e74c3c
}
li:hover span {
width: 30px;
opacity: 1.0;
}
input {
font-size: 18px;
width: 100%;
padding: 13px 13px 13px 20px;
box-sizing: border-box;
border: 3px solid rgba(0,0,0,0);
color: #2980b9;
background-color: #e4e4e4;
}
input:focus {
background: white;
border: 3px solid green;
/*OUTLINE OF INPUT BOX
outlin: none; */
}
.fa-plus {
float: right;
}
#container {
width: 360px;
margin: 60px auto;
background: #d3d3d3;
box-shadow: 0 0 3px rgba(0,0,0,0.1);
}
.completed {
color: red;
text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>ToDo List</title>
<link rel="stylesheet" type="text/css" href="utd.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
</head>
<body>
<iframe src="http://free.timeanddate.com/clock/i5zr5d5i/n1991/szw110/szh110/hoc09f/hbw0/hfc09f/cf100/hnce1ead6/fas30/fdi66/mqc000/mql15/mqw4/mqd98/mhc000/mhl15/mhw4/mhd98/mmc000/mml10/mmw1/mmd98/hhc00f/hhs2/hmcf00/hms2/hsv0" frameborder="0" width="110" height="110"></iframe>
<div id="container">
<h1>To-do List <i class="fa fa-plus"></i></h1>
<form id="task-list">
<input type="text" placeholder="Add a To-Do" id="task">
</form>
<ol id="sortable">
<li><span><i class="fa fa-trash"></i></span> EXAMPLE</li>
</ol>
</div>
<script type="text/javascript" src="Utd.js"></script>
</body>
</html>
//check of spec
$("ol").on("click", "li", function(){
$(this).toggleClass("completed");
});
//click on X to delete To-DO
$("ol").on("click", "span", function(event){
$(this).parent().fadeOut(500,function(){
// $(this).remove();
});
//event.stopPropagation();
});
$("input[type='text'").keypress(function(event){
if(event.which === 13) {
//grabbing the text typed
var todoText = $(this).val();
$(this).val("");
//create a new LI and add to UL
$("ol").append("<li><span><i class='fa fa-trash'></i></span> " + todoText +"</li>")
}
});
$(".fa-plus").click(function(){
$("input[type='text'").fadeToggle();
});
h1 {
background: #2980b9;
color: white;
margin: 0;
padding: 10px 15px;
text-transform: uppercase;
font-size: 24px;
font-weight: normal;
}
iframe {
float: left;
}
ol {
/* THE BULLET POINTS
list-style: none;
*/
margin: 0;
padding: 0;
font-size: 18px;
}
body {
background-color: rgb(13, 168, 108);
}
li {
background: #fff;
height: 30px;
line-height: 30px;
color: #666;
}
li:nth-child(2n){
background: #d3d3d3;
}
span {
height: 30px;
width: 0px;
margin-right: 20px;
text-align: center;
color:white;
display: inline-block;
transition: 0.2s linear;
opacity:0;
background: #e74c3c
}
li:hover span {
width: 30px;
opacity: 1.0;
}
input {
font-size: 18px;
width: 100%;
padding: 13px 13px 13px 20px;
box-sizing: border-box;
border: 3px solid rgba(0,0,0,0);
color: #2980b9;
background-color: #e4e4e4;
}
input:focus {
background: white;
border: 3px solid green;
/*OUTLINE OF INPUT BOX
outlin: none; */
}
.fa-plus {
float: right;
}
#container {
width: 360px;
margin: 60px auto;
background: #d3d3d3;
box-shadow: 0 0 3px rgba(0,0,0,0.1);
}
.completed {
color: red;
text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>ToDo List</title>
<link rel="stylesheet" type="text/css" href="utd.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
</head>
<body>
<div id="container">
<h1>To-do List <i class="fa fa-plus"></i></h1>
<input type="text" placeholder="Add a To-Do" id="task">
<ol id="sortable">
<li><span><i class="fa fa-trash"></i></span> EXAMPLE</li>
</ol>
</div>
<script type="text/javascript" src="Utd.js"></script>
</body>
</html>
After making edits in browser, simply save the page as HTML with different file name. Your selected values will be saved.

"Odd" behavior when clicking on li elements

I'm trying to add a class to dynamically generated <li> elements, but it has a very strange behavior. With a single <li> it works perfectly, but after adding an another element, the class attribute will be added without value. After adding the third <li> it will work again (basically it works only if the number of the <li> elements is odd).
var JSTasker = {
updateTaskCounter: function() {
var taskCount = $('div#tasks ul').children().not('li.completed').size();
$('span#task_counter').text(taskCount);
},
sortTasks: function() {
var taskList = $('div#tasks ul');
var allCompleted = $(taskList).children('.completed');
allCompleted.detach();
allCompleted.appendTo(taskList);
},
updatePage: function() {
this.updateTaskCounter();
this.sortTasks();
}
};
$(document).ready(function() {
$('input#task_text').focus();
$('form#add_task').on('submit', function(event) {
event.preventDefault();
var taskText = $('input#task_text').val();
var taskItem = "<li>" + taskText + "</li>";
$('div#tasks ul').append(taskItem);
$('input#task_text').val(null);
JSTasker.updatePage();
$('div#tasks ul').on('click', 'li', function(event) {
event.preventDefault();
$(this).toggleClass('completed');
JSTasker.updatePage();
});
});
});
h1,
h2,
ul,
li {
margin: 0px;
padding: 0px;
}
html {
background: #333;
font-family: 'Gill Sans Light', 'Helvetica', 'Arial';
font-size: 90%;
}
body {
width: 400px;
margin: 10px auto;
border: 1px solid #EEE;
background: #F6F6F6;
padding: 10px 20px;
}
fieldset {
border: 2px solid #CCC;
padding: 10px;
margin: 10px 0px 0px 0px;
}
input[type=text] {
width: 300px;
padding-right: 20px;
}
input[type=submit] {} #tasks {
margin: 20px 0px 0px 0px;
}
h2 {
margin-bottom: 10px;
}
h2 span#task_counter {
font-size: 80%;
color: #999;
}
#tasks ul {
list-style-type: none;
}
#tasks ul li {
padding: 6px 10px 3px 20px;
height: 1.6em;
}
#tasks ul li:hover {
background: #FFF8DC;
text-decoration: underline;
}
#tasks ul li.completed {
background: url('icons/accept.png') no-repeat 0px 5px;
text-decoration: line-through;
color: #999;
}
.trash {
float: right;
padding: 2px;
}
.trash:hover {
background: #F99;
cursor: pointer;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Tasker</title>
<link rel='stylesheet' type="text/css" href='JSTasker.css' />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="JSTasker.js"></script>
</head>
<body>
<h1>JSTasker</h1>
<form id='add_task'>
<fieldset>
<legend>Add a Task</legend>
<input type='text' name='task_text' id='task_text' />
<input type='submit' name='add_button' value='Add' />
</fieldset>
</form>
<div id='tasks'>
<h2>Your Tasks <span id='task_counter'></span></h2>
<ul>
</ul>
</div>
</body>
</html>
This is the problematic part:
$('div#tasks ul').on('click', 'li', function(event) {
event.preventDefault();
$(this).toggleClass('completed');
JSTasker.updatePage();
});
The application is based on this tutorial.
add onclick handler outside form submit, right now your onclick event is being initialized every time you submit the form. but $().on() is for dynamic binding and you need to call it only once
$(document).ready(function() {
$('input#task_text').focus();
$('form#add_task').on('submit', function(event) {
event.preventDefault();
var taskText = $('input#task_text').val();
var taskItem = "<li>" + taskText + "</li>";
$('div#tasks ul').append(taskItem);
$('input#task_text').val("");
JSTasker.updatePage();
});
$('div#tasks ul').on('click', "li", function(event) {
event.preventDefault();
$(this).toggleClass('completed');
JSTasker.updatePage();
});
});
You are binding click event to li for every click of add button. Take this code out and it will work. It was working for odd number of elements because it will bind event odd times. lets say you added 3 lis and hence it will call click event 3 times. first time add class, then remove and then add class again. But it will fail for even number of lis as it will first add class and then remove it.
var JSTasker = {
updateTaskCounter: function() {
var taskCount = $('div#tasks ul').children().not('li.completed').size();
$('span#task_counter').text(taskCount);
},
sortTasks: function() {
var taskList = $('div#tasks ul');
var allCompleted = $(taskList).children('.completed');
allCompleted.detach();
allCompleted.appendTo(taskList);
},
updatePage: function() {
this.updateTaskCounter();
this.sortTasks();
}
};
$(document).ready(function() {
$('input#task_text').focus();
$('form#add_task').on('submit', function(event) {
event.preventDefault();
var taskText = $('input#task_text').val();
var taskItem = "<li>" + taskText + "</li>";
$('div#tasks ul').append(taskItem);
$('input#task_text').val(null);
JSTasker.updatePage();
});
$('div#tasks ul').on('click', 'li', function(event) {
event.preventDefault();
$(this).toggleClass('completed');
JSTasker.updatePage();
});
});
h1,
h2,
ul,
li {
margin: 0px;
padding: 0px;
}
html {
background: #333;
font-family: 'Gill Sans Light', 'Helvetica', 'Arial';
font-size: 90%;
}
body {
width: 400px;
margin: 10px auto;
border: 1px solid #EEE;
background: #F6F6F6;
padding: 10px 20px;
}
fieldset {
border: 2px solid #CCC;
padding: 10px;
margin: 10px 0px 0px 0px;
}
input[type=text] {
width: 300px;
padding-right: 20px;
}
input[type=submit] {} #tasks {
margin: 20px 0px 0px 0px;
}
h2 {
margin-bottom: 10px;
}
h2 span#task_counter {
font-size: 80%;
color: #999;
}
#tasks ul {
list-style-type: none;
}
#tasks ul li {
padding: 6px 10px 3px 20px;
height: 1.6em;
}
#tasks ul li:hover {
background: #FFF8DC;
text-decoration: underline;
}
#tasks ul li.completed {
background: url('icons/accept.png') no-repeat 0px 5px;
text-decoration: line-through;
color: #999;
}
.trash {
float: right;
padding: 2px;
}
.trash:hover {
background: #F99;
cursor: pointer;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Tasker</title>
<link rel='stylesheet' type="text/css" href='JSTasker.css' />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="JSTasker.js"></script>
</head>
<body>
<h1>JSTasker</h1>
<form id='add_task'>
<fieldset>
<legend>Add a Task</legend>
<input type='text' name='task_text' id='task_text' />
<input type='submit' name='add_button' value='Add' />
</fieldset>
</form>
<div id='tasks'>
<h2>Your Tasks <span id='task_counter'></span></h2>
<ul>
</ul>
</div>
</body>
</html>
Your code works with only odd numbers of tasks because you add a new click handler to every <li> each time you submit the form. That means that when you have two <li>s, you call toggleClass twice, and get nowhere. You can confirm this by adding alert("hi") to your current code after the toggleClass call.

problems displaying Javascript message within <p>

I using jQuery-UI sortable which works fine. The problem that I am having is that the message "New order saved!" or "Save failed" is not displaying in the < p > area. The function is either not executing or something.
Below is the code for the .aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link href="jQuery/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="jQuery/jquery.min.js" type="text/javascript"></script>
<script src="jQuery/jquery-ui.min.js" type="text/javascript"></script>
<script src="jQuery/json2.js" type="text/javascript"></script>
<script src="jQuery/jquery-ui-i18n.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#sortable").sortable({ placeholder: "vacant" });
$("#sortable").disableSelection();
$("#sortable input[type=text]").width($("#sortable img").width() - 10);
$("#sortable label").mouseover(function () {
$(this).parent().children("input[type=text]").show().val($(this).html());
$(this).hide();
});
$("#sortable input[type=text]").mouseout(function () {
$(this).parent().children("label").show().html($(this).val());
$(this).hide();
});
$(".ContainerDiv").hover(
function () {
$(this).find(".deleteClass").show();
},
function () {
$(this).find(".deleteClass").hide();
});
$(".deleteClass").click(function () {
$(this).closest("li").remove();
});
$("#orderPhoto").click(function () {
var photos = $.map($("li.ui-state-default"), function (item, index) {
var imgDetail = new Object();
imgDetail.Id = $(item).find("img").attr("id");
imgDetail.Caption = $(item).find("label").html();
imgDetail.Order = index + 1;
return imgDetail;
});
var jsonPhotos = JSON.stringify(photos);
$.ajax({
type: "POST",
contentType: "application/json",
data: "{photos:" + jsonPhotos + "}",
url: "WebService.asmx/updatePhoto",
dataType: "json",
success: function (data) {
if (data.d === "saved") {
$("<p>").text("New order saved!")
.addClass("success").appendTo("#left");
} else {
$("<p>").text("Save failed")
.addClass("failure").appendTo("#left");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
});
});
</script>
<style type="text/css">
#sortable
{
list-style-type: none;
margin: 0;
padding: 0;
}
#sortable li
{
position: relative;
margin: 3px 3px 3px 0;
padding: 1px;
float: left;
text-align: left;
}
#sortable .vacant
{
border: 3px dotted #66d164;
width: 150px;
height: 175px;
background-color: #fff;
}
#outerWrap
{
width: 1004px;
margin: auto;
position: relative;
background-color: #eee;
border: 1px solid #999;
}
#outerWrap:after
{
content: ".";
display: block;
visibility: hidden;
clear: both;
}
#left
{
width: 218px;
float: left;
}
#images
{
margin: 0;
padding: 0;
float: left;
width: 786px;
}
h1
{
font: italic normal 24px Georgia, Serif;
text-align: center;
margin: 10px 0;
}
p
{
margin: 0;
font: 12px Arial, Sans-serif;
padding: 0 10px;
}
.deleteClass
{
/* PhotoListItem is relative so relative to it */
position: absolute;
top: 1px;
right: 3px;
background: black;
color: Red;
font-weight: bold;
font-size: 12px;
padding: 5px;
opacity: 0.60;
filter: alpha(opacity="60");
margin-top: 3px;
display: none;
cursor: pointer;
}
.deleteClass:hover
{
opacity: 0.90;
filter: alpha(opacity="90");
}
.image_resize
{
width: 150px;
height: 150px;
border: 0;
}
.success, .failure
{
margin: 0 0 0 10px;
padding: 4px 0 4px 26px;
position: absolute;
bottom: 18px;
font-weight: bold;
}
.success
{
background: url('../img/tick.png') no-repeat 0 1px;
color: #12751c;
}
.failure
{
background: url('../img/cross.png') no-repeat 0 0;
color: #861b16;
}
</style>
</head>
<body>
<form id="form2" runat="server">
<div id="outerWrap">
<div id="left">
<h1>
Image Organiser</h1>
<p>
Re-order the images by dragging an image to a new location. Your changes will be
saved automatically.</p>
</div>
<div id="images">
<asp:ListView ID="ListViewAlbumPhotoView" runat="server" GroupItemCount="15">
<LayoutTemplate>
<ul id="sortable">
<li id="groupPlaceholder" runat="server">1</li>
</ul>
</LayoutTemplate>
<GroupTemplate>
<tr id="itemPlaceholderContainer" runat="server">
<td id="itemPlaceholder" runat="server">
</td>
</tr>
</GroupTemplate>
<ItemTemplate>
<li class="ui-state-default">
<div class="ContainerDiv">
<div class="deleteClass">
X</div>
<img id='<%#Eval("photo_id")%>' src='<%# "uploads/" + Eval("photo_file_name")%>'
alt="" class="image_resize" />
<div style="height: 25px; margin-top: 3px">
<label>
<%# Eval("photo_title")%></label>
<input type="text" style="display: none" />
</div>
</div>
</li>
</ItemTemplate>
</asp:ListView>
<input type="button" id="orderPhoto" value="Save change" />
</div>
</div>
</form>
</body>
</html>
The problem is with
success: function (data) {
if (data.d === "saved") {
$("<p>").text("New order saved!")
.addClass("success").appendTo("#left");
} else {
$("<p>").text("Save failed")
.addClass("failure").appendTo("#left");
}
},
Could someone tell me how to message display in the < p > area?
Any help would be greatly appreciated.
Thanks
Be sure to add the closing tag as well:
$("<p></p>").text("Save failed").addClass("failure").appendTo("#left");
Update: Also make sure the success function is even being called--Use a tool like Firebug (Firefox) or Developer tools in Chrome or Safari to inspect net traffic to see what the result of your call is.
You don't use brackets around the p inside the jquery function
try $('p')
Are you trying to update the single paragraph element already there? Or do you want to insert
a new paragraph element every single time. If you want the second case, just combine everything at once.
if (data.d === "saved") {
$("<p class='success'>New order saved!</p>").appendTo("#left");
}
else {
$("<p class='failure'>Save failed!</p>").appendTo("#left");
}

Categories