Change data status for all elements on click - javascript

In the first function, an item is marked read or unread by clicking the .activity__button. The next function is to change the status of all of the items to read.
Why isn't the function iterating over each item and button?
var button = $(".activity__button");
var item = $(".activity__item");
When I press the button to change the status to read, nothing happens. Additionally, how do you handle a second click of the button to change all back to unread?
$(".activity__button").on("click", function(e) {
e.stopPropagation();
e.preventDefault();
var icon = $(this).find("svg");
var status = $(this).attr("data-status");
if (status === "read") {
$(this)
.removeClass("activity__button--read")
.attr("data-status", "unread");
icon.attr("data-icon", "envelope");
$(this)
.closest(".activity__item")
.removeClass("activity__item--read")
.attr("data-status", "unread");
} else {
$(this)
.addClass("activity__button--read")
.attr("data-status", "read");
icon.attr("data-icon", "envelope-open");
$(this)
.closest(".activity__item")
.addClass("activity__item--read")
.attr("data-status", "read");
}
});
$(".section").on("click", ".mark", function(e) {
e.stopPropagation();
e.preventDefault();
var button = $(".activity__button");
var item = $(".activity__item");
var icon = button.find("svg");
var status = button.attr("data-status");
if (status === "unread") {
button.addClass("activity__button--read").attr("data-status", "read");
icon.attr("data-icon", "envelope-open");
item.addClass("activity__item--read").attr("data-status", "read");
}
});
.activity__item {
position: relative;
height: 100px;
width: 300px;
border: 1px solid whitesmoke;
margin-top: -1px;
}
.activity__button {
cursor: pointer;
padding: 1rem;
font-size: 21px;
}
.activity__button svg {
color: #f8971d;
}
.activity__button.activity__button--read svg {
color: #47a877;
}
.activity__item--read {
background: #fafafa !important;
}
button {
padding: 12px;
margin: 1rem;
}
<script src="https://pro.fontawesome.com/releases/v5.8.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class "section">
<button class="mark">Mark as Read</button>
<div>
<div class="activity__item">
<div class="activity__button" data-status="unread"><i class="fas fa-envelope"></i>
</div>
</div>
<div class="activity__item">
<div class="activity__button" data-status="unread"><i class="fas fa-envelope"></i>
</div>
</div>
<div class="activity__item activity__item--read">
<div class="activity__button activity__button--read" data-status="read">
<i class="fas fa-envelope-open"></i>
</div>
</div>
<div class="activity__item">
<div class="activity__button" data-status="unread">
<i class="fas fa-envelope"></i>
</div>
</div>
</div>
</div>

Working example (with other classes)
var open = 'fas fa-envelope-open';
var close = 'fas fa-envelope';
$(".activity__button").off().on('click', function() {
var status = $(this).data('status');
if( status == 'unread' ) {
$(this).data('status', 'read').empty().html('<i class="' + open + '"></i>').addClass('activity__button--read');
$(this).parent().addClass('activity__item--read');
} else {
$(this).data('status', 'unread').empty().html('<i class="' + close + '"></i>').removeClass('activity__button--read');
$(this).parent().removeClass('activity__item--read');
}
});
$('.mark').off().on('click', function() {
$(".activity__button").each( function() {
$(this).data('status', 'read').empty().html('<i class="' + open + '"></i>').addClass('activity__button--read');
$(this).parent().addClass('activity__item--read');
});
});
See here:
https://jsfiddle.net/8yk9a7rn/

Related

Issues with JavaScript list [duplicate]

This question already has answers here:
Clicking a button within a form causes page refresh
(11 answers)
Is there a way to add/remove several classes in one single instruction with classList?
(16 answers)
Closed 8 months ago.
I am assigned to create this to do list using eventlisteners and using JavaScript. My HTML and CSS are given to me however I believe I may be confusing my Id's with each other. The expectation is that a new item is added to the list, can be deleted from the list when clicked on the trashcan, and the input is cleared. Any advice on what I am missing would be helpful... I've been staring at this for 7hrs now.
const todoObjectList = [];
class toDo_Class {
constructor(item) {
this.ulElement = item;
}
add() {
const todoInput = document.querySelector("#todo-input").value;
if (todoInput == "") {
alert("Nothing was entered!");
} else {
const todoObject = {
id: todoObjectList.length,
todoText: todoInput,
isDone: false,
};
todoObjectList.unshift(todoObject);
this.display();
document.querySelector("#todo-input").value = '';
}
}
done_undone(x) {
const selectedTodoIndex = todoObjectList.findIndex((item) => item.id == x);
console.log(todoObjectList[selectedTodoIndex].isDone);
todoObjectList[selectedTodoIndex].isDone == false ? todoObjectList[selectedTodoIndex].isDone == true : todoObjectList[selectedTodoIndex].isDone = false;
this.display();
}
deleteElement(z) {
const selectedDelIndex = todoObjectList.findIndex((item) => item.id == z);
todoObjectList.splice(selectedDelIndex, 1);
this.display();
}
display() {
this.ulElement.innerHTML = "";
todoObjectList.forEach((object_item) => {
const liElement = document.createElement("li");
const delBtn = document.createElement("i");
liElement.innerText = object_item.todoText;
liElement.setAttribute("data-id", object_item.id);
delBtn.setAttribute("data-id", object_item.id);
delBtn.classList.add("fas fa-trash-alt");
liElement.appendChild(delBtn);
delBtn.addEventListener("click", function(e) {
const deleteId = e.target.getAttribute("data-id");
toDoList.deleteElement(deleteId);
});
liElement.addEventListener("click", function(e) {
const selectedId = e.target.getAttribute("data-id");
toDoList.done_undone(selectedId);
});
if (object_item.isDone) {
liElement.classList.add("checked");
}
this.ulElement.appendChild(liElement);
});
}
}
const listSection = document.querySelector("#todo-ul");
toDoList = new toDo_Class(listSection);
document.querySelector("#todo-btn").addEventListener("click", function() {
toDoList.add();
});
document.querySelector("#todo-input").addEventListener("keydown", function(e) {
if (e.keyCode == 13) {
toDoList.add();
}
});
body {
background-color: #34495e;
font-family: "Lato", sans-serif;
}
button {
margin: 0 auto;
float: right;
}
.centered {
margin: 0 auto;
width: 80%;
}
.card {
margin: 50px auto;
width: 18rem;
}
i {
float: right;
padding-top: 5px;
}
<html lang="en">
<body>
<div class="card">
<div class="card-body">
<h3 class="card-title">Today's To Do List</h3>
<form id="todo-form">
<div class="form-group">
<input type="text" class="form-control" id="todo-input" placeholder="What else do you need to do?">
</div>
<div class="form-group">
<input type="submit" id="todo-btn" class="btn btn-secondary btn-block" value="Add Item To List">
</div>
</form>
</div>
<ul class="list-group list-group-flush" id="todo-ul">
<li class="list-group-item">Pick up groceries <i class="fas fa-trash-alt"></i>
</li>
</ul>
</div>
</body>
</html>

I was trying to make a to-do list using javascript but unable to append the selected option

Aim was to take input and create radio buttons and label dynamically like a list which when checked goes to bottom while label name coming from the input textfield that we write. I was able to do this with the radio button but not with the label. Please help me out I'm new here.
[Fiddle] (http://jsfiddle.net/wju6t7k3/2/)
<div id = "container" >
<div class="row">
<div class="col-12">
<input id = "txt" type = "text" placeholder="Add new.." >
<button id="btn" value = "add" type = "button" onClick = "add()" >
</button>
</div>
<div id="done" class="col-12">
</div>
</div> <!-- row -->
<script>
//js
var j = 0;
var textval="";
function getInputValue(){
// Selecting the input element and get its value
inputVal = document.getElementById("txt").value;
// Displaying the value
alert(inputVal);
}
function add() {
if (document.getElementById('txt').value != '') {
j++;
var title = document.getElementById('txt').value;
var node = document.createElement('div');
node.innerHTML = '<input type="checkbox" class="checkbox-round" id="check' + j + '" name="check' + j + '"><label for="check' + j + '">' + title + '</label>';
document.getElementById('done').appendChild(node);
}
}
input = document.getElementById("txt");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
document.getElementById("btn").click();
textval =this.value;
onfocus=this.value='';
}
});
function countChecked(event) {
alert(textval);
alert("balle");
getInputValue();
$(this).parent().parent().append(this).append('<label>textvalh</label>').append('<br>');
}
$("#container").on( "click", "input[type=checkbox]", countChecked );
function getForm(event) {
event.preventDefault();
var form = document.getElementById("task").value;
console.log(form);
}
</script>
You have to make a container or a parent element for the checkbox and its label to have more control of it.
and if you want to separate the checkbox that is checked, then make another div element to make a separation.
Here's an example, this is based on your code:
//js
var j = 0;
function add() {
if (document.getElementById('txt').value != '') {
j++;
var title = document.getElementById('txt').value;
var node = document.createElement('div');
node.innerHTML = '<div><input type="checkbox" class="checkbox-round" id="check' + j + '" name="check' + j + '"><label for="check' + j + '">' + title + '</label></div>';
document.getElementById('done').appendChild(node);
}
}
input = document.getElementById("txt");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
document.getElementById("btn").click();
textval = this.value;
this.value='';
}
});
function countChecked(event) {
const isChecked = event.currentTarget.checked;
// Get parent of checkbox which is the closest <div> element
const checkbox_parent = $(event.currentTarget).closest('div');
if (isChecked) // Move element to div with ID = selected
checkbox_parent.appendTo('#selected')
else // Move element to div with ID = done
checkbox_parent.appendTo('#done')
}
$('#container').on('change', 'input[type="checkbox"]', countChecked)
input, input:active{
border:none;
cursor: pointer;
outline: none;
}
::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: blue;
}
::-moz-placeholder { /* Firefox 19+ */
color: blue;
}
:-ms-input-placeholder { /* IE 10+ */
color: blue;
}
:-moz-placeholder { /* Firefox 18- */
color: blue;
}
button{
display:none;
}
.checkbox-round {
width: 1.3em;
height: 1.3em;
background-color: white;
border-radius: 50%;
vertical-align: middle;
border: 1px solid #ddd;
-webkit-appearance: none;
outline: none;
cursor: pointer;
}
.checkbox-round:checked {
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" >
<div class="row">
<div class="col-12" style="border: dashed red 3px;">
<input id = "txt" type="text" placeholder="Add new.." />
<button id="btn" value="add" type="button" onClick ="add()">Add</button>
<div id="done" class="col-12" style="border: solid purple 3px;">
</div>
<div id="selected" class="col-12" style="border: solid gray 3px;">
</div>
</div>
</div> <!-- row -->
</div>
Happy Coding!

how to change text color and back ground color of span when ng click function occur

I have two button. Today and tomorrow. And i have ng click function for both button. What i need is by default my button back ground color will be white. and text color will be red.
When i click my totday button , i need my back ground color to chnage to blue, and text color have to chnage to white.
and if i press tomorrow button this same design have to apply for this button. and my today button have to be default color. How to do this :
here my code :
<div class="row" style="height: 52px;">
<div class="col col-50" style="border-right: 1px #ccc solid; padding-top: 17px; text-align: center;" ng-click="GetDetails()" id="1">
<span class="assertive" style="margin: 0px;color: #B90143;">TODAY</span>
</div>
<div class="col col-50" style="padding-top: 17px;text-align: center;" ng-click="GetTomorrowDetails()">
<span class="assertive" style="margin: 0px;color: #B90143; width: 100%;">TOMORROW</span>
</div>
</div>
My controller for ng-cilck for both button :
$scope.GetDetails = function(){
$ionicLoading.hide();
$scope.orders.length = 0
MydeliveryFactory.save($scope.orderInfo, function(response){
var AllOrderValues = response.allorders;
for (var i = AllOrderValues.length - 1; i >= 0; i--) {
if(AllOrderValues[i].dateAdded == todaydate && AllOrderValues[i].monthAdded == todayMonth ) {
$scope.orders.push(AllOrderValues[i]);
$ionicLoading.hide();
console.log($scope.orders);
}
}
$window.localStorage.setItem("MyDeliverYOrders", JSON.stringify($scope.orders));
});
}
$scope.GetTomorrowDetails = function(){
$ionicLoading.show();
$scope.orders.length = 0
MydeliveryFactory.save($scope.orderInfo, function(response){
var Allvalues = response.allorders;
for (var i = Allvalues.length - 1; i >= 0; i--) {
if(Allvalues[i].dateAdded == tomorrowdate && Allvalues[i].monthAdded == tomorrowMonth) {
$scope.orders.push(Allvalues[i]);
$ionicLoading.hide();
console.log($scope.orders);
}
}
$window.localStorage.setItem("MyDeliverYOrders", JSON.stringify($scope.orders));
});
}
You can toggle classes with ng-class and $scopes.
I have added ng-class="{'active':active.today}" in button, it means active class will be added when active.today is true and will remove when active.today is false, same for tomorrow button,
and in js function is just toggling $scope between true and false.
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.active = {};
$scope.GetDetails = function() {
$scope.active.tomorrow = false;
$scope.active.today = true;
}
$scope.GetTomorrowDetails = function() {
$scope.active.today = false;
$scope.active.tomorrow = true;
}
});
.active {
background: blue;
color: #fff!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl" class="row" style="height: 52px;">
<div class="col col-50" style="border-right: 1px #ccc solid; padding-top: 17px; text-align: center;" ng-click="GetDetails()" id="1">
<span class="assertive" ng-class="{'active':active.today}" style="margin: 0px;color: #B90143;">TODAY</span>
</div>
<div class="col col-50" style="padding-top: 17px;text-align: center;" ng-click="GetTomorrowDetails()">
<span class="assertive" ng-class="{'active':active.tomorrow}" style="margin: 0px;color: #B90143; width: 100%;">TOMORROW</span>
</div>
</div>
Have a look at ngClass, using this you will be able to dynamically change the class assigned to your buttons.
Your button html could look a little like this:
<button ng-class="[btn, btn-primary, {today: active-class}]" ng-click="GetDetails()">Today</button>
<button ng-class="[btn, btn-primary, {!today: active-class}]" ng-click="GetTomorrowDetails()">Tomorrow</button>
You controller, something like this:
$scope.today = true;
$scope.GetDetails = function() {
$scope.today = true;
}
$scope.GetTomorrowDetails = function() {
$scope.today = false;
}
Add a common class to your button and provide them the default css.
<div class="row" style="height: 52px;">
<div class="btn col col-50" style="border-right: 1px #ccc solid; padding-top: 17px; text-align: center;" ng-click="GetDetails($event)" id="1">
<span class="assertive" style="margin: 0px;color: #B90143;">TODAY</span>
</div>
<div class="btn col col-50" style="padding-top: 17px;text-align: center;" ng-click="GetTomorrowDetails($event)">
<span class="assertive" style="margin: 0px;color: #B90143; width: 100%;">TOMORROW</span>
</div>
</div>
.btn {
background-color: white;
color: red;
}
And in your Controller, handle your click handlers:
$scope.GetDetails = function(event) {
$scope.defaultColors();
event.target.style.backgroundColor = "blue";
event.target.style.color = "white";
};
$scope.GetTomorrowDetails = function(event) {
$scope.defaultColors();
event.target.style.backgroundColor = "blue";
event.target.style.color = "white";
};
$scope.defaultColors = function() {
[].slice.call(document.getElementsByClassName("btn")).forEach(function(el, i) {
el.style.backgroundColor = "white";
el.style.color = "red";
});
};

Node Jquery load pages into div error

// Userlist data array for filling in info box
var userListData = [];
// DOM Ready =============================================================
$(document).ready(function() {
// Populate the user table on initial page load
populateTable();
// Username link click
$('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);
// Add User button click
$('#btnAddUser').on('click', addUser);
// Delete User link click
$('#userList table tbody').on('click', 'td a.linkdeleteuser', deleteUser);
//Set Default page to Home.html
$('#content').load('views/home.html');
//Call navBar function
navBar();
projectBtn();
});
// Functions =============================================================
//Navbar function
function navBar() {
$('ul#navtest li a').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
function projectBtn() {
$('a.projectbutton').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
// Fill table with data
function populateTable() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON( '/users/userlist', function( data ) {
// Stick our user data array into a userlist variable in the global object
userListData = data;
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function(){
tableContent += '<tr>';
tableContent += '<td>' + this.username + '</td>';
tableContent += '<td>' + this.email + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#userList table tbody').html(tableContent);
});
};
// Show User Info
function showUserInfo(event) {
// Prevent Link from Firing
event.preventDefault();
// Retrieve username from link rel attribute
var thisUserName = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);
// Get our User Object
var thisUserObject = userListData[arrayPosition];
//Populate Info Box
$('#userInfoName').text(thisUserObject.fullname);
$('#userInfoAge').text(thisUserObject.age);
$('#userInfoGender').text(thisUserObject.gender);
$('#userInfoLocation').text(thisUserObject.location);
};
// Add User
function addUser(event) {
event.preventDefault();
// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addUser input').each(function(index, val) {
if($(this).val() === '') { errorCount++; }
});
// Check and make sure errorCount's still at zero
if(errorCount === 0) {
// If it is, compile all user info into one object
var newUser = {
'username': $('#addUser fieldset input#inputUserName').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'age': $('#addUser fieldset input#inputUserAge').val(),
'location': $('#addUser fieldset input#inputUserLocation').val(),
'gender': $('#addUser fieldset input#inputUserGender').val()
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
// Clear the form inputs
$('#addUser fieldset input').val('');
// Update the table
populateTable();
}
else {
// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);
}
});
}
else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;
}
};
// Delete User
function deleteUser(event) {
event.preventDefault();
// Pop up a confirmation dialog
var confirmation = confirm('Are you sure you want to delete this user?');
// Check and make sure the user confirmed
if (confirmation === true) {
// If they did, do our delete
$.ajax({
type: 'DELETE',
url: '/users/deleteuser/' + $(this).attr('rel')
}).done(function( response ) {
// Check for a successful (blank) response
if (response.msg === '') {
}
else {
alert('Error: ' + response.msg);
}
// Update the table
populateTable();
});
}
else {
// If they said no to the confirm, do nothing
return false;
}
};
.border {
border: 4px solid black; }
.back2 {
background-color: #232323; }
.marginleft {
margin-left: 8%; }
.margin {
margin-right: 4%;
margin-left: 4%;
margin-top: 2%;
margin-bottom: 2%; }
.padding {
padding: 1%; }
.margintop {
margin-top: 1%; }
.margintop2 {
margin-top: 5%; }
.iconmargintop {
margin-top: 50px; }
.fill {
height: 100%;
width: 100%; }
p {
color: #ffffff; }
label {
color: #ffffff; }
h1 {
color: #ffffff; }
h2 {
color: #ffffff; }
th {
color: #ffffff; }
span {
color: #ffffff; }
h3 {
color: #ffffff; }
.projectseltext {
padding: 1%;
margin: 1%; }
.background {
background-color: #333333;
position: relative;
height: 100%; }
#blacktext {
color: black; }
.disablelink {
pointer-events: none;
cursor: default; }
.nav {
background-color: #b2b2b2; }
.nav a {
color: #ffffff;
font-size: 11px;
font-weight: bold;
padding: 14px 10px;
text-transform: uppercase; }
.nav li {
display: inline; }
.back1 {
background-color: #0c0c0c; }
.fit {
height: 100%;
width: 100%; }
.well {
background-color: #333333; }
.backg1 {
background-color: #333333; }
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="project">
<div class="container-fluid row">
<a href="#" title="projectnew" class="projectbutton">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin col-md-3" style="width:150px;" />
<h1 class="margin" style="margin-top:75px;">New Projects</h1>
</div>
</a>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<link rel="stylesheet" href="stylesheets/bootstrap.min.css" />
<link rel="stylesheet" href="stylesheets/main.css" />
<script src="build/js/jquery-2.2.4.min.js"></script>
<script src="build/js/bootstrap.min.js"></script>
<script src="build/js/global.js"></script>
<title></title>
</head>
<body class="background">
<div class="container-fluid nav navbar-inverse">
<ul id="navtest" class="margintop">
<li>
Home
</li>
<li>
Projects
</li>
<li>
Contact
</li>
<li>
Resume
</li>
<li>
About
</li>
<li>
Database
</li>
</ul>
</div>
<div id='content' class="tab-content" />
</body>
</html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="projectnew">
<div class="row">
<div class="container col-md-12 margintop marginleft">
Back
</div>
<div class="container-fluid margin">
<a href="" data-toggle="tab">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin" style="width:150px" />
<h1 class="margin">Comming soon.</h1>
</div>
</a>
</div>
</div>
</div>
</body>
</html>
This file is temporary, i know the contents wont do anything.
The function navBar works perfectly, however when trying to apply the same method to another class and div it seems to fail.
Whenever i click on the projectbutton class it redirects to error.html. For some reason the javascript is not seeing/handling the class on click and the href being an unsupported type redirects me to error.html. However i'm not sure what is wrong with my code.
welcome;
In your HTML code, <a href="projectnew" class="projectbutton"> you have an href for your a element, if you click on this, it will go to the page "www.yourdomain.com/projectnew" since this page does not exist, you will be redirected to your error page...
To solve this problem, you should use preventDefault, in order to prevent your link element to operate things that you do not want.
$('a.projectbutton').click(function(event) {
event.preventDefault();
var page = $(this).attr('href');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
I did not try it out, but it should work.
Read more about preventDefault: https://api.jquery.com/event.preventdefault/
OR;
Since the main problem is your href attributes in your a elements, try to remove them;
Home
Use title as your specifier in your JS;
$('a.projectbutton').click(function() {
var page = $(this).attr('title'); //changed this into title.
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});

Add div below another div

I have a requirement to add 5 divs one by one on each click of a div button. ( the new div should be added below the existing div)
I done the code, but the news ones are getting attached on the top of existing div. please help to correct this.
I have another button which removes the added divs one by one(new ones to be remove first)
here is my code.
<div class="clearFix"></div>
<div id="containershowmore" >
<div id="dragbtnmore" style="cursor: default;">Show more buttons</div>
<div id="dragbtnless" style="cursor: default;">Show Fewer buttons</div>
</div>
<div class="toAdd" style="display:none;" >
<div id="dragdashboardmain" style="cursor: pointer;">dash</div></div>
<div class="toAdd" style="display:none;" >
<div id="dragrcalendar" style="cursor: pointer;">Calendar</div></div>
<div class="toAdd" style="display:none;">
<div id="dragresourcelist" style="cursor: pointer;">Rlist</div></div>
<div class="toAdd" style="display:none;">
<div id="dragdailynotes" style="cursor: pointer;">D Notes</div></div>
<div class="toAdd" style="display:none;">
<div id="dragweeklynotes" style="cursor: pointer;">W Notes</div></div>
script:
$("#dragbtnmore").click(function () {
$('.toAdd').each(function () {
if ($(this).css('display') == 'none') {
$(this).css('display', 'block');
return false;
}
});
var i = 0;
$('.toAdd').each(function () {
if ($(this).css('display') != 'none') {
i++;
}
});
if (i == 5)
$('#dragbtnmore').click(function () { return false; });
});
$("#dragbtnless").click(function () {
$('.toAdd').each(function () {
if ($(this).css('display') == 'block') {
$(this).css('display', 'none');
return false;
}
});
var i = 0;
$('.toAdd').each(function () {
if ($(this).css('display') != 'block') {
i++;
}
});
if (i == 5)
$('#dragbtnless').click(function () { return false; });
$('#dragbtnless').click(function () { return true; });
});
$("#containershowmore").mouseleave(function () {
$(this).hide();
});
function showmore() {
document.getElementById('containershowmore').style.display = "block";
}
style:
#containershowmore
{
margin-top: -75px;position: relative;margin-left: 160px;background-color: #b1dafb;z-index: 1;
width: 125px;
float: right;
padding-left: 5px;
}
.toAdd
{
background-color: blue;
margin-top: -55px;
position: relative;
margin-bottom: 14px;
}
*I referred this Fiddle *
**Solution:
Thankyou Shivam Chopra for helping me . Thanks a TON!! :)
for others, HEre is the solution**
jsfiddle.net/coolshivster/YvE5F/12
Remove margin top from both the div.
#containershowmore
{
position: relative;margin-left: 160px;background-color: #b1dafb;z-index: 1;
width: 125px;
float:right;
padding-left: 5px;
}
#dragbtnmore{
margin-bottom:10px;
border:1px solid black;
}
.toAdd
{
height:20px;
width:70px;
background-color: blue;
position: relative;
margin-bottom: 14px;
}
Then, it will work accordingly.
Here, the code : http://jsfiddle.net/coolshivster/YvE5F/
I have rewritten your code according to your requirement.
Some explanation about the code
I have create a parent div element with id="Add-element" that covers every element which contains class .toAdd .
Then I created data attribute for every div containing class .toAdd .
Now, I display the element one by one. But after first element. Every other element will prepend on the parent div i.e., #Add-element class.
Now, the code which I have rewritten.
jsfiddle link : http://jsfiddle.net/YvE5F/10/

Categories

Resources