Strike element of array by click on it (JS) - javascript

I have html where I display array from js
Here is code
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<div id ="container">
<div id="data"></div>
<input id="text" type=text/>
<button id="get" onclick="getValue()">Update</button>
</div>
Here js code
var tasks = ["Task 1", "Task 2"];
$.each(tasks, function(){
$('#data').append('<li class="clickable">'+this + '</li>');
});
I get element from list like this
$(document).on('click', '.clickable', function() {
var str = $(this);
});
And now I need to strike it via js. How I can do this?

You can do this to strike the element on click:
var tasks = ["Task 1", "Task 2"];
$.each(tasks, function(){
$('#data').append('<li class="clickable">'+this + '</li>');
});
$(document).on('click', '.clickable', function() {
$(this).css("text-decoration", "line-through");
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<div id ="container">
<div id="data"></div>
<input id="text" type=text/>
<button id="get" onclick="getValue()">Update</button>
</div>
But if you want to add and remove strike on click each time then use this:
var tasks = ["Task 1", "Task 2"];
$.each(tasks, function(){
$('#data').append('<li class="clickable">'+this + '</li>');
});
$(document).on('click', '.clickable', function() {
$(this).toggleClass('strikeClass');
});
.strikeClass{
text-decoration: line-through;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<div id ="container">
<div id="data"></div>
<input id="text" type=text/>
<button id="get" onclick="getValue()">Update</button>
</div>

You have two options.
1) Wrap around del tag
$(document).on('click', '.clickable', function() {
var str = $(this);
srt.wrap("<del></del>");
});
2) Add style attribute
$(document).on('click', '.clickable', function() {
var str = $(this);
str.css("text-decoration", "line-through");
});

If you need to remove element, simply do onClick="$(this).remove();"
$(document).ready(function() {
$(document).on('click', '.clickable', function() {
$(this).remove();
});
var tasks = ["Task 1", "Task 2"];
$.each(tasks, function() {
$('#data').append('<li class="clickable">' + this + '</li>');
});
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<div id="container">
<div id="data"></div>
<input id="text" type=text/>
<button id="get" onclick="getValue()">Update</button>
</div>

i do not understand what you mean
$(document).on('click', '.clickable', function() {
var txt = this.textContent;
this.innerHTML = txt.strike();
});

Related

How can I use effects like `.show('slow')`

How can I use .append() with effects like .show('slow')
Having effects on append doesn't seem to work at all, and it give the same result as normal show(). No transitions, no animations.
$(function () {
var html = "<div id='str'>Hello</div>";
$('#btn').click(function () {
$('#cont').append(html);
});
});
<button id='btn'>click</button>
<div id='cont'></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
try this:
$(function () {
$('#str').hide();
var html = "";
$('#btn').click(function () {
$('#str').toggle(1000);
});
});
<button id='btn'>click</button>
<div id='cont'></div>
<div style="display:none" id='str'>Hello</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you really are desperate about the adding HTML
$(function () {
$('#str').hide();
var html = "";
$('#btn').click(function () {
$('str').innerHTML ="Hello"
$('#str').toggle(1000);
if($('str').style.display=="none"){
$('str').innerHTML =""
}
});
});
<button id='btn'>click</button>
<div id='cont'></div>
<div style="display:none" id='str'></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

add event to element after it remove itself and append itself again

I tried to remove a button and alert() when i click it, then the function will append a 'same' button to a container div, after searching senior's legacy,
i tried to use on()/live()/delegate()/ unfortunately they not work.
<body>
<div id="container"></div>
<hr>
<button onclick="clicked()">Other one</button>
<hr>
</body>
<script>
$(document).ready(function(){
var i = 0;
$("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!</button>");
$("[id='btn_sub']").delegate(this,"click",function(){
$("#container").empty();
$("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!"+i+"</button>");
i++;
});//tried click/on click/live
});
function clicked(){
alert(1);
}
</script>
Finally, in this example, the clicked function put out of $(document).ready() and the part of alert worked.
Is there any other method to do the same effect?
and why on()/live()/delegate()/ not work?
Thanks.
First off $("[id='btn_sub']") can be replaced with $("#btn_sub"), then it's actually better to use a class as you might have many buttons.
This is a working example as an illustration: https://codepen.io/antoniandre/pen/XoNNpO
$(document).ready(function(){
$("#container").on("click", '.btn_sub', function() {
removeButton(this);
});
});
function addButton() {
$("#container").append("<button class='btn_sub'>Delete Me!</button>");
}
function removeButton(btn) {
btn.remove();
}
With the on() bound on the container, you actually make sure any matching button .btn_sub will get this event attached to them when they are created in the future.
Regarding live, it does the same as on but is now deprecated so you can forget it. https://api.jquery.com/live/#live-events-handler
Use on function to attach event.http://api.jquery.com/on/
$(document).ready(function () {
var i = 0;
$("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!</button>");
$("#container").on("click", "[id='btn_sub']", function(){
$("#container").empty();
$("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!" + i + "</button>");
i++;
});
});
function clicked() {
alert(1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id="container"></div>
<hr>
<button onclick="clicked()">Other one</button>
<hr>
</body>
var i = 0;
var btn = "<button id='btn_sub' onclick='clicked()'>Click Me!</button>";
($(function(){
$("#container").append(btn);
$("#container").on("click", '#btn_sub', function() {
$("#container")
.empty()
.append($(btn).text($(btn).text() + " " + i++));
});
}));
function clicked() {
alert(i);
}
<body>
<div id="container"></div>
<hr>
<button onclick="clicked()">Other one</button>
<hr>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Event Delegation, need for the row number to show up on the added items

I need for the row number to show up on the added items to the list
<!DOCTYPE html>
<html>
<head>
<title>JavaScript & jQuery - Chapter 7: Introducing jQuery -
Example</title>
<link rel="stylesheet" href="css/c7.css" />
</head>
<body>
<div id="page">
<h1 id="header">List</h1>
<h2>Buy groceries <span id="counter"></span></h2>
<ul>
<li id="Row: 1" class="hot"><em>fresh</em> figs</li>
<li id="Row: 2" class="hot">pine nuts</li>
<li id="Row: 3" class="hot">honey</li>
<li id="Row: 4">balsamic vinegar</li>
</ul>
<div id="newItemButton"><button href="#" id="showForm">new item</button>
</div>
<form id="newItemForm">
<input type="text" id="itemDescription" placeholder="Add description" />
<input type="submit" id="add" value="add" />
</form>
</div>
<script src="js/jq.js"></script>
<script src="js/ex.js"></script>
</body>
</html>
Js
$(function() {
var ids = '';
var $listItems = $('li');
$listItems.on('mouseover click', function() {
ids = this.id;
$listItems.children('span').remove();
$(this).append(' <span class="priority">' + ids + '</span>');
});
$listItems.on('mouseout', function() {
$(this).children('span').remove();
});
});
$(function() {
var $list, $newItemForm, $newItemButton;
var item = '';
$list = $('ul');
$newItemForm = $('#newItemForm');
$newItemButton = $('#newItemButton');
$('li').hide().each(function(index) {
$(this).delay(450 * index).fadeIn(1600);
});
function updateCount() {
var items = $('li[class!=complete]').length;
$('#counter').text(items);
}
updateCount();
$newItemButton.show();
$newItemForm.hide();
$('#showForm').on('click', function() {
$newItemButton.hide();
$newItemForm.show();
});
$newItemForm.on('submit', function(e) {
e.preventDefault();
var text = $('input:text').val();
$list.append('<li>' + text + '</li>');
$('input:text').val('');
updateCount();
});
$list.on('click', 'li', function() {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete === true) {
$this.animate({
opacity: 0.0,
paddingLeft: '+=180'
}, 500, 'swing', function() {
$this.remove();
});
} else {
item = $this.text();
$this.remove();
$list
.append('<li class=\"complete\">' + item + '</li>')
.hide().fadeIn(300);
updateCount();
}
});
});
When you hover your mouse over the rows, the row number would appear trailing
(appear after) the text of that row. After the mouse leaves the row, the row number should disappear. The “NEW ITEM” button in the example let you insert new rows. After new rows are inserted, you need to make sure the effect you implemented above works for the newly added rows also.
You can view my page here: http://et791.ni.utoledo.edu/~gaugsbu/asg4/asg4.2.html
Rules for event delegation are pretty simple. You have to delegate events to an element/document that is a permanent asset and target the elements that are dynamic.
You can't store $listItems since that collection won't include new ones added after code is run.
It seems your <ul> is permanent so do something like:
$('ul').on('mouseover click', 'li', function(event){
// do stuff
}).on('mouseout','li', function(event){
// do stuff
})

Elements within dynamically created of <div> on each button click is not properly overridden

I am trying to create a comment box where on each submit a new is dynamically created. The inner elements of the <div> being 3 buttons Edit, Post, Cancel and a close icon(image). These are also dynamically created. I finally append them all together. The below code would generate something like the below image on two submits. The error I'm facing is that, whatever <div>'s close icon/button is clicked, always the last <div> is being affected. Here I tried to close 'Hi' but 'hello' is being affected.Also there is a duplication of the <div> on even comments.
Kindly help me correct these issues.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<textarea id="ta" rows="30" cols="30" readonly></textarea>
<br>
<input type="textbox" id="tb"></input><br>
<button onclick="add()">Submit</button><br>
<script type="text/javascript">
var newDiv="",i=1,ta="";
function add() {
i++;
ta=document.getElementById('ta');
newDiv = document.createElement("div");
newDiv.id = "d"+i;
newDiv.style.display="block";
newTa = document.createElement("input");
newTa.type="text"
newTa.id = "t"+i;
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
newTa.style.display="block";
newTa.onclick=function(){
newP.style.visibility="visible";
newImg.style.visibility="visible";
newBut1.style.visibility="visible";
newButt1.style.visibility="visible";
};
// document.querySelector('body').addEventListener('click', function(event) {
newP=document.createElement("BUTTON");
newP.id="p"+i;
newP.innerHTML="Edit";
newP.style.visibility="hidden";
newP.style.display="inline";
newP.onclick=function()
{
newTa.removeAttribute('readonly'); // only needed the first time
newTa.readOnly = false;
//newTa.setAttribute("readOnly","false");
//newTa.readonly='false';
//newP.innerHTML="wrng";
}
newImg=document.createElement("IMG");
newImg.id="i"+i;
newImg.src="http://www.freeiconspng.com/uploads/close-icon-30.png";
newImg.style.width="20%";
newImg.style.height="20%";
newImg.alt="close";
newImg.style.visibility="hidden";
newImg.style.display="inline";
newImg.onclick=function()
{
newDiv.innerHTML="";
//newDiv.remove();
}
newBut1=document.createElement("button");
newBut1.id="b"+i;
newBut1.innerHTML="Post";
newBut1.style.visibility="hidden";
newBut1.style.display="inline";
newBut1.onclick=function(){
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
}
newButt1=document.createElement("button");
newButt1.id="bt"+i;
newButt1.innerHTML="Cancel";
newButt1.style.visibility="hidden";
newButt1.onclick=function(){
newTa.value=document.getElementById('tb').value;
newTa.readonly='true';
}
newDiv.appendChild(newTa);
newDiv.appendChild(newP);
newDiv.appendChild(newImg);
newDiv.appendChild(newBut1);
newDiv.appendChild(newButt1);
var b=""
b="t"+i;
ta.appendChild(newDiv);
document.getElementById(b).value=document.getElementById('tb').value;
}
</script>
</body>
</html>
Try this code. I have changed textarea to div.
Initial i to 0 instead of 1. You can also set it to 1. It won't affect the functionality.
Some variables were global, I have changed them to local variable now like newDiv,newP, newImg etc.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<!--<textarea id="ta" rows="30" cols="30" readonly></textarea>-->
<div id="ta"></div>
<br>
<input type="textbox" id="tb"></input><br>
<button onclick="add()">Submit</button><br>
<script type="text/javascript">
var i=0,ta="";
function add() {
(function(){
i++;
var temp_i = i;
ta=document.getElementById('ta');
var newDiv = document.createElement("div");
newDiv.id = "d"+temp_i;
newDiv.style.display="block";
newTa = document.createElement("input");
newTa.type="text"
newTa.id = "t"+temp_i;
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
newTa.style.display="block";
newTa.onclick=function(){
console.log(temp_i);
console.log(i);
newP.style.visibility="visible";
newImg.style.visibility="visible";
newBut1.style.visibility="visible";
newButt1.style.visibility="visible";
};
// document.querySelector('body').addEventListener('click', function(event) {
var newP=document.createElement("BUTTON");
newP.id="p"+temp_i;
newP.innerHTML="Edit";
newP.style.visibility="hidden";
newP.style.display="inline";
newP.onclick=function()
{
newTa.removeAttribute('readonly'); // only needed the first time
newTa.readOnly = false;
//newTa.setAttribute("readOnly","false");
//newTa.readonly='false';
//newP.innerHTML="wrng";
}
var newImg=document.createElement("IMG");
newImg.id="i"+temp_i;
newImg.src="http://www.freeiconspng.com/uploads/close-icon-30.png";
newImg.style.width="20%";
newImg.style.height="20%";
newImg.alt="close";
newImg.style.visibility="hidden";
newImg.style.display="inline";
newImg.onclick=function()
{
newDiv.innerHTML="";
//newDiv.remove();
}
var newBut1=document.createElement("button");
newBut1.id="b"+temp_i;
newBut1.innerHTML="Post";
newBut1.style.visibility="hidden";
newBut1.style.display="inline";
newBut1.onclick=function(){
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
}
var newButt1=document.createElement("button");
newButt1.id="bt"+temp_i;
newButt1.innerHTML="Cancel";
newButt1.style.visibility="hidden";
newButt1.onclick=function(){
newTa.value=document.getElementById('tb').value;
newTa.readonly='true';
}
newDiv.appendChild(newTa);
newDiv.appendChild(newP);
newDiv.appendChild(newImg);
newDiv.appendChild(newBut1);
newDiv.appendChild(newButt1);
var b=""
b="t"+temp_i;
ta.appendChild(newDiv);
document.getElementById(b).value=document.getElementById('tb').value;
})();
}
</script>
</body>
</html>
Why not you use jquery to minimize your code campaign. Below is the code which will fix your problem.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<br>
<div class="container">
<input type="textbox" id="tb"><br>
<button>Edit</button><button>Post</button><button class="cancel">Cancel</button><br />
</div>
<button class="submit">Submit</button><br>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.submit').click(function() {
var element = '<div class="container">'+'<input type="textbox" id="tb"><br>'+
'<button>Edit</button><button>Post</button><button class="cancel">Cancel</button><br /></div>';
$('.submit').before(element);
});
$('body').delegate('.cancel', 'click', function() {
$(this).parent().remove();
});
});
</script>
</body>
</html>
Thanks

2 containers cancel eachother

i would like to know how i can prevent two containers from canceling. the codes are almost the same i just changed a few things it doesn't mater which one i put first but the second one is not working if i switched them around the one that i put first works but not the second one. I'm using toggle to display one at a time. I'm just going to post a small part of my code.
JavaScript for first part
<script>
var z = 1; //value to make div overlappable
$('#addText').click(function (e) {
/** Make div draggable **/
$('<div />', {
class: 'ui-widget-content',
appendTo: '.container',
draggable: {
containment: 'parent',
start: function( event, ui ) {
$(this).css('z-index', ++z);
}
}
});
});
$(document).on("dblclick", '.text', function()
{
$(this).hide(); $(this).closest('.item').find('.edit_text').val($(this).text()).show();
});
$(document).on("click", ".edit_text", function()
{
return false;
});
$(document).on("click", function()
{
var editingText = $('.edit_text:visible');
if (editingText.length)
{
editingText.hide();
editingText.closest('.item').find('.text').text($(editingText).val()).show();
}
});
var count = 1;
var selectedDraggable;
ko.bindingHandlers.draggable={
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).draggable();
$(element).addClass('item' + count);
count++;
$(element).on('click', function () {
selectedDraggable = $(this);
})
}
};
var vm=function(){
var self=this;
self.items=ko.observableArray();
self.textContent = ko.observable('');
self.init=function(){
self.items([]);
}
self.remove=function(item){
console.log(item);
self.items.remove(item);
}
self.addNew = function() {
self.items.push( self.textContent() );
self.textContent('');
}
self.init();
}
ko.applyBindings(new vm());
JavaScript for second part
var z = 1; //value to make div overlappable
$('#addText').click(function (e) {
/** Make div draggable **/
$('<div />', {
class: 'ui-widget-content',
appendTo: '.container4',
draggable: {
containment: 'parent',
start: function( event, ui ) {
$(this).css('z-index', ++z);
}
}
});
});
$(document).on("dblclick", '.text1', function()
{
$(this).hide(); $(this).closest('.item1').find('.edit_text1').val($(this).text()).show();
});
$(document).on("click", ".edit_text1", function()
{
return false;
});
$(document).on("click", function()
{
var editingText = $('.edit_text1:visible');
if (editingText.length)
{
editingText.hide();
editingText.closest('.item1').find('.text1').text($(editingText).val()).show();
}
});
var count = 1;
var selectedDraggable;
ko.bindingHandlers.draggable={
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).draggable();
$(element).addClass('item1' + count);
count++;
$(element).on('click', function () {
selectedDraggable = $(this);
})
}
};
var vm=function(){
var self=this;
self.items1=ko.observableArray();
self.textContent1 = ko.observable('');
self.init=function(){
self.items1([]);
}
self.remove=function(item){
console.log(item);
self.items1.remove(item);
}
self.addNew1 = function() {
self.items1.push( self.textContent1() );
self.textContent1('');
}
self.init();
}
ko.applyBindings(new vm());
toggle
$("#show_first").click(function(){
$(".firstdiv").toggle();
$(".seconddiv").hide();
});
$("#show_second").click(function(){
$(".secoddiv").toggle();
$(".firstdiv").hide();
});
HTML for toggle
<button type="button" id="show_first">Display Front</button>
<button type="button" id="show_second">Display Back</button>
HTML for container and input text (first)
<div class="firstdiv"><center>Front</center>
<div class="container1" style=" float: left;" >
<p align="center"><textarea data-bind="value: textContent" Placeholder="Type text to append" rows="4" cols="21"></textarea>
<button type="button" data-bind="click: addNew">Create</button></p>
<div id="box" class="container" style="float:left;">
<div data-bind="foreach:items" class="fix_backround">
<div class="item" data-bind="draggable:true,droppable:true">
<center><span class="text" data-bind="text:$data"></span><input class="edit_text"/></center></div></div></div></div></div>
HTML for container and input text (second)
<div class="seconddiv"><center>second</center>
<div class="container3" style=" float: left;" >
<p align="center"><textarea data-bind="value: textContent1" Placeholder="Type text to append" rows="4" cols="21"></textarea>
<button type="button" data-bind="click: addNew1">Create</button></p></div>
<div id="box1" class="container4" style="float:left;">
<div data-bind="foreach:items1" class="fix_backround1">
<div class="item1" data-bind="draggable:true,droppable:true">
<center><span class="text1" data-bind="text:$data"></span><input class="edit_text1"/></center></div></div></div></div></div>
Script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<link rel="stylesheet"href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet"href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="http://circletype.labwire.ca/js/circletype.js"></script><script src="http://tympanus.net/Development/Arctext/js/jquery.arctext.js"></script>
You are including jQuery, Knockout, and jQuery-UI each twice. That's probably not the problem, but it's not good.
You're using jQuery to control which block displays, and that's a Knockout no-no. It is Knockout's job to manipulate the DOM. Have a look at Knockout templates, or the if binding for ways of controlling what displays.
It looks like you have a typo in your toggle js for the seconddiv class. You're missing an 'n' in your jquery call for it: secoddiv. If this code is straight from the source that may be the problem.

Categories