Selecting <li> item using jQuery after doubleclick - javascript

Here's what I'm trying to do:
I have an input field one can use to add entries to a todo list. I use JQuery to display a sorted list of entries after the user clicks 'Add'. I also made the list sortable (You can change the order by mouse drag using jQuery.) Now what I want to bold an individual list item when it is double-clicked. Somehow I'm not getting the jQuery to select the right item...
Here's my code.
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src='script.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<title>Tadum</title>
</head>
<body>
<h2>Tadum - The ToDo List</h2>
<h3>Enter New ToDos</h3>
<form id="addForm">
<input type="text" name="ToDoListItem"></input>
</form>
<div id="button">Add!</div>
<h3>Your ToDos</h3>
<ol class="todolist"></ol>
</body>
</html>
CSS:
.todolist li{
font-weight: normal;
}
.todolist {
font-family:garamond;
color:#cc0000;
}
Javascript
$(document).ready(function() {
$('#button').click(function(){
var toAdd = $('input[name=ToDoListItem]').val();
$('.todolist').append('<li class="item">'+toAdd+'</li>');
$('#addForm')[0].reset();
});
$('ol').sortable();
$('ol').css('cursor', 'pointer');
$('.todolist li').dblclick(function(){
$(this).css('font-weight', 'bold');
});
});
NOTE:
Somehow what works is if I replace the .list li in jQuery and in the CSS stylesheet with a simple ol. Then a doubleclick displays all items in the list (which is, of course, not what I want). But somehow I can't figure out how to only select the individual <li> that is doubleclicked with jQuery...
(I also tried a bunch of variations on this. For example, only use 'li' to select the doubleclicked item or use 'ol li', or '.item li'. None of them work.)

You need to bind the dblclick event handler to the newly added list items, like this:
$(document).on('dblclick', '.todolist li', function(){
$(this).css('font-weight', 'bold');
});
Please note that this doesn't toggle the style, but just makes them bold on double click. If you double click again it won't do anything.
Also if I may suggest some other changes to your JavaScript code: Your form can be normally submitted like any other form, for the purposes of this to do list anyways. I've also added a label to the HTML <form> for accessibility purposes.
$(document).ready(function() {
$('#addForm').submit(function(e){
e.preventDefault();
$('.todolist').append('<li class="item">' + $('#ToDoListItem').val() + '</li>');
$(this)[0].reset();
});
$('ol').sortable().css('cursor', 'pointer');
$(document).on('dblclick', '.todolist li', function() {
$(this).css('font-weight', 'bold');
});
});
HTML
<form id="addForm">
<label for='ToDoListItem'>Item:</label>
<input type="text" id="ToDoListItem" />
<button type='submit'>Add!</button>
</form>

You are adding the li items after the document was created. So you need to use "on" method so that you can trigger the click on the newly created items afterwards.
$(document).ready(function() {
$('#addForm').submit(function(e){
e.preventDefault();
var toAdd = $('#ToDoListItem').val();
$('.todolist').append('<li class="item">'+toAdd+'</li>');
$('#ToDoListItem').reset();
});
$('ol').sortable().css('cursor', 'pointer');
$(document).on('dblclick','li.item',function(){
$(this).css('font-weight', 'bold');
});
});

Related

Hide/show child element onClick

I am building a "edit profile" page.
Here is what I want to do:
In each section, the employer will be shown and the edit form will be hidden.
When I click the "edit employer" button, the edit form will be shown and the employer will be hidden.
Here is what I did using jQuery. It does not work when I click on the "edit employer" button. I do not know why this does not work.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="edit">
<form class="editForm">
employer: <input type="text" value="Citigroup" />
</form>
<div class="contents">Employer: Citigroup</div>
<button class="editButton">Edit Employer</button>
</div>
<script>
$('div.edit').each(function(i) {
$(this).children('.editForm').hide();
})
$('div.edit').each(function() {
$(this).children('.editButton').click(function() {
$(this).children('.editForm').show();
$(this).children('.contents').hide();
});
})
</script>
</body>
</html>
The $(this) inside the click function contains the local instance of the $(this).children('.editButton'). For that reason your code is not finding any .editForm elements.
For this to work you could do something like this:
<script>
$('div.edit').each(function(i) {
$(this).children('.editForm').hide();
})
$('div.edit').each(function() {
var $this = $(this);
$(this).children('.editButton').click(function() {
$this.children('.editForm').show();
$this.children('.contents').hide();
});
})
</script>
If I may I would improve the code with some more changes:
<script>
$('.edit .editForm').hide(); // this will hide all instances of .editForm
$('.edit .editButton').click(function() { //assign 1 handler for all cases
$(this).siblings('.editForm').show(); // show the sibling edit form
$(this).siblings('.contents').hide(); // hide the sibling contents element
});
</script>
Reference:
Sibling Selector: https://api.jquery.com/siblings/#siblings-selector
The problem is the this inside the click handler referring to the button, not the div.edit. Here's one way to fix this:
$('div.edit').each(function(i) {
$(this).children('.editForm').hide();
});
$('div.edit').each(function() {
var $self = $(this);
$(this).children('.editButton').click(function() {
$self.children('.editForm').show();
$self.children('.contents').hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="edit">
<form class="editForm">
employer:
<input type="text" value="Citigroup" />
</form>
<div class="contents">Employer: Citigroup</div>
<button class="editButton">Edit Employer</button>
</div>
You don't need to use .each() at all. Just do an .click() event on the class of .editButton and use this to find its parent. If you want to make a toggle, you're going to have to make use of a new class or something of that nature to make a conditional statement off of.
//This will hide *ANY* .editForm elements
$('.editForm').hide();
//This will fire off of *ANY* editButton clicks.
$('.editButton').click(function() {
var form = $(this).closest('.edit'); //Get the wrapper
if(form.hasClass('open')) { //Check to see if it is open or not
form.removeClass('open').addClass('close'); //Toggle Classes
form.find('.editForm').show();
form.find('.contents').hide();
} else {
form.removeClass('close').addClass('open');
form.find('.editForm').hide();
form.find('.contents').show();
}
});
I like to use closest and find more than parent and children (respectively). They can go 1-many layers up or down and search the hierarchy for whatever you're looking for, rather than parent and children going up or down a single layer.
If you are inserting your .edit form after the DOM loads, you're going to need to bind your click event to the document
$(document).on('click', '.editButton', function() {
var form = $(this).closest('.edit');
form.find('.editForm').hide();
form.find('.contents').show();
});

jquery - click, append, load, slideDown not displaying as expected

I'm trying to implement, what I thought would be a simple click, load, slideDown scenario. But I can't get the slideDown part to display.
I have the following two buttons:
<div>
<fieldset id="btn">
<input class="databasebtn" type="submit" name="nameDatabaseBtn" id="db1" data-id=1" VALUE="DB1"/></br>
<input class="databasebtn" type="submit" name="nameDatabaseBtn" id="db2" data-id="2" VALUE="DB2"/></br>
</fieldset>
</div>
I then have the following jQuery:
$(document).ready(function()
{
$('.databasebtn').on('click',function()
{
$(this).append("<div id='btnlist'></div>");
$('#btnlist').slideDown("200",function()
{
$('#btnlist').load("test78b.php");
});
})
});
The idea being that I click the button, I append the #btnlist div to the button, and fill the new div with the contents of test78b.php, which should generate a list of checkboxes.
It all works fine, except that I can't see the checkboxes. If I look at the code in the background it is all there, it just wont show up.
If I include 'test78b.php' separately it displays as expected.
Is there something I am missing?
You can not append div to a button, you can append div to a parent in this case fildset with this code
<script type="text/javascript">
$(document).ready(function() {
$('.databasebtn').on('click',function(){
$(this).parent().append("<div id='btnlist'></div>");
$('#btnlist').slideDown('slow',function(){
$('#btnlist').load("your page");
})
})
});
</script>
or you can use insertBefore to append div before butoon clicked with this code
<script type="text/javascript">
$(document).ready(function() {
$('.databasebtn').on('click',function(){
$("<div id='btnlist'></div>").insertBefore($(this))
$('#btnlist').slideDown('slow',function(){
$('#btnlist').load("your page");
})
})
});
</script>
or append div to the body tag with this other code
<script type="text/javascript">
$(document).ready(function() {
$('.databasebtn').on('click',function(){
$("<div id='btnlist'></div>").appendTo('body')
$('#btnlist').slideDown('slow',function(){
$('#btnlist').load("your page");
})
})
});
</script>
and then, for a correct html code,you shouldn't have multiple items on the same page with the same id. The div added via script should not have id btnlist but class="btnlist"
DEMO http://jsfiddle.net/TWQbD/4/
$('.databasebtn').on('click',function() {
$(this).next('.databasetext').append("<div class='btnlist'>test78b.php</div>");
$(this).next('.databasetext').find('.btnlist').last().slideDown("1000");
});

Selecting all children of an element and fadeing them out using jQuery?

I am using the following HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Project Quiz</title>
<link rel="stylesheet" type="text/css" href="z/baseCss.CSS">
<script src="/jquery-1.9.1.min.js"></script>
<script src="/baseJS.js"></script>
</head>
<body>
<div id=header></div>
<div id=contain>
<h1>Welcome to my web application</br>
Please enter your name, click 'continue' and have fun</h1>
<form>
<input type="text" id="name" value="John Doe"/>
</form>
<div class="awesome">Continue</div><br/>
</div>
<div id=footer></div>
</body>
</html>
and a code of jQuery:
$(document).ready(function(){
$("input")
.focus(function(){
$(this).css('outline-color','#559FFF');
$(this).blur(function(){
$(this).css("outline-color","#FF0000");
});
});
$("input").click(function(){
var value = $(this).val(function(){
$(this).html("");
});
});
$(".awesome").click(function(){
b._slide(1000);
});
var b = $("div:nth-child(2)");
alert(b);
});
My problem is that I can't figure it out how to select all children of <div id="contain"> and just make them fade out when I click my div button which is the one with the "awesome" class.
This is what I have tried so far:
$(".contain").each(function(){
$(this).fadeOut(1000);
});
but it didnt work also i tried:
$(".contain").children(function(){
$(this).fadeOut(1000);
});
Same result here.
What am I doing wrong? I only need to fadeOut the content of <div id="contain"> and keep everything else the same as it is.
You need to use:
$("#contain").children().fadeOut(1000);
$(this) is your selector
.children() selects all the children of an element
.fadeOut(1000) fades out the current selection
Your attempts were wrong because:
$(".contain").each(function(){ $(this).fadeOut(1000); });
Selects all the elements with class .contain and hides them
$(".contain").children(function(){ $(this).fadeOut(1000); });
Selects the elements with class .contain, and then you're passing a function to .children() which it does not handle.
Note, in your case contain is an ID and not a class.
beside shangeing the "." to "#" form the jquery selector, if you don't need to insert anything else or display new content into <div id="contain">, you can just do this
$("#contain").fade(1000);
all the child will fade too

Changing a div's id on click

How do I add an onClick listener to a div.
I want to change the name of a div to divclass active if it was inactive previously & then remove the word 'active' if user click on the list again.
I'm at a loss how to do this.
This is what I've tried so far
<script>
$function tog(){
$(this).toggleClass('active');
return false;
}
$(function() {
var dd = new DropDown( $('#dd') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown-4').removeClass('active');
});
});
</script>
where the div whose class name I want to change is defined as below
<div id="dd" onclick="tog()" class="wrapper-dropdown-4">
<!--something-->
</div>
I've tried this..
<html>
<head>
<script>
$('#dd').on('click', function(){
$(this).toggleClass('active')
});
</script>
<style>
.active {
color: red;
}
</style>
</head>
<body>
<div id="dd" class="wrapper-dropdown-4">
ddddd
</div>
</body>
</html>
What's wrong with this now?
I'm inspecting the element id via chrome developer's tool & I don't see any change using this code. So, can anyone please help?
Thanks. :)
The only script you need is
$(function(){
$('#dd').on('click', function(){
$(this).toggleClass('active')
});
});
Demo: Fiddle
you have to pass the object $(this) is not recognizable , use tog(this)
<script>
function tog(obj)
{
$(obj).toggleClass('active');
return false;
}
$(function() {
var dd = new DropDown( $('#dd') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown-4').removeClass('active');
});
});
</script>
<div id="dd" onclick="tog(this)" class="wrapper-dropdown-4">
<!--something-->
</div>
not the best way to do it, you can bind the event ,by registering the click in the event.

Remove style from selected span/text in div

Consider this snippet:
<div>
<span style="color:red;">a</span>
<span style="color:blue;">a</span>
<span style="color:white;">a</span>
</div>
How can you remove style from selected by user text?
Edited: to add clarifications from OP:
Thank you for your answers!
I had to be more precise. Sorry for that.
What do I mean by "selected by user text": selected/highlighted with mouse.
I have many divs with spans inside(just like it is below-no extra ids,classes for spans:/).
[...]
<div>
<span style="color:red;">a</span>
<span style="color:blue;">b</span>
<span style="color:white;">c</span>
</div>
<div>
<span style="color:red;">d</span>
<span style="color:blue;">a</span>
<span style="color:white;">a</span>
</div>
[...]
What I would like to achieve: user selects with mouse "ab", click button(input type=button) which remove style from selected span/spans. Similar behavior like it is in TinyMCE.
I'm not sure what you mean by "selected by user text", but if you mean that you want the user to be able to click on the text to remove its color, you could do it this way with jQuery:
Try it out: http://jsfiddle.net/v24fZ/
$(function() {
$('div > span').click(function() {
$(this).removeAttr('style');
});
});
Note that this will affect all <span> elements that are a child of a <div>, so better would be to place an ID attribute on the <div> to make sure you have the right one.
Try it out: http://jsfiddle.net/v24fZ/1/
<div id="myID"><span style="color:red;">a</span><span style="color:blue;">a</span><span style="color:white;">a</span></div>
then
$(function() {
$('#myID > span').click(function() {
$(this).removeAttr('style');
});
});
Also note that this will remove all inline styles. If you only want to remove the color, then do this:
Try it out: http://jsfiddle.net/v24fZ/2/
$(function() {
$('#myID > span').click(function() {
$(this).css('color', '');
});
});
http://api.jquery.com/removeAttr/
http://api.jquery.com/css/
http://api.jquery.com/click/
"Remove style from selected by user text"
If you mean selecting by using a click event, it should be something like this:
var oldState = ""; //Code is untested, but I've written something similar recently
var $prevDiv;
$('#parentContainer span').click(function() {
if(!$(this).hasClass('selected')) //tracking what is currently selected.
{
if($prevDiv != null)
{
$prevDiv.removeClass('selected');
$prevDiv.attr('style', oldState);
}
$prevDiv = $(this);
$(this).addClass('selected');
oldState = $(this).attr('style');
$(this).attr('style', '');
}
else
{
//do nothing unless you need some reselected logic
}
}
I think #patrick dw covered the actual api for changing the attribute quite nicely, so I won't repeat it.
I totally agree with patrick.
You may want to try the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
<span style="color:red;">a</span>
<span style="color:blue;">a</span>
<span style="color:white;">a</span>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function(){
$("span").click(function(){
$(this).removeAttr("style");
});
});
</script>
</body>
</html>

Categories