JQuery show delete button on appended div - javascript

I have so far able to remove each appened elements using .remove() function of JQuery. my problem is the delete button is always showing on the first element.
I want to hide the delete button on first element and show the delete button when I append a new element.
I have set the delete button on the first element to
.delete-button:first-child{
display:none;
}
in my css but all succeeding appends do not show the delete button..
how can I do this with JQuery can it be done using CSS only?

li:first-child .delete-button { display:none }
<ul>
<li>
First <button class="delete-button">Delete</button>
</li>
<li>
Second <button class="delete-button">Delete</button>
</li>
</ul>
Making assumptions on your markup since none was provided. You can accomplish it using css.

My interpretation of your requirement: If there is only one item, do not show a delete button; if there are multiple items, show a delete button for every item.
Your attempt didn't work because .delete-button:first-child selects all elements with the delete-button class that are also the first-child of their parent element. Presumably this would be all of your buttons.
You can instead use the :only-of-type selector on the elements that contain the delete buttons, e.g., assuming they have the item class:
.item:only-of-type .delete-button { display: none; }
Or if they are li elements:
li:only-of-type .delete-button { display: none; }
That way if the item/li/whatever is the only item then its delete button will be hidden automatically, but as soon as you add additional items the delete button will be shown automatically for all items.
Here's a simple demo with a bit of JS to mock up the add and delete functionality:
$("#parent").on("click", ".delete-button", function() {
$(this).parent().remove();
});
$(".add-button").on("click", function() {
$("#parent").children().first().clone().appendTo("#parent");
});
.item:only-of-type .delete-button { display: none; }
.item { margin: 3px; padding: 2px; width: 100px; border: thin black solid; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="add-button">Add Item</button>
<div id="parent">
<div class="item">
<button class="delete-button">Delete</button>
<div>An item</div>
</div>
</div>

You can try,
div ul:not(:first-child) {
.delete-button{
display:none;
}
}

You might wanna consider browser compatibility before using CSS - Browser support for CSS :first-child and :last-child
Having said that, With jQuery you can write an event handler to change css of all the child elements except the last.
Consider this example from jQuery: How to listen for DOM changes?
$("element-root").bind("DOMSubtreeModified", "CustomHandler");

Yes, Its possible by css only. I hope this snippet helps.
$(document).on('click','#AppendList', function(){
$("ul").append('<li>List <button class="delete-button">Delete</button></li>');
})
li .delete-button { display:none }
li:last-child .delete-button { display: inline-block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
First <button class="delete-button">Delete</button>
</li>
<li>
Second <button class="delete-button">Delete</button>
</li>
</ul>
<hr>
<button type="button" id="AppendList">Add List</button>

Related

Which JS technique: select parent of targeted element?

I'm not sure that the terms in the question are correct; however I have some HTML (and unfortunately, I am stuck with its structure):
<div>
<ul>
<li>Turn left</li>
<li>Turn right</li>
</ul>
</div>
<div class="possible-outcome">
<span id="turn-left"></span>
<p>You step into a puddle.</p>
</div>
<div class="possible-outcome">
<span id="turn-right"></span>
<p>You fall into a ditch.</p>
</div>
What I would like is all possible-outcome divs to become hidden by having:
div.non-actual-outcome {display: none;}
applied to them, as soon as the user selects one of the hyperlinks, except for the div containing the span with the target id, which should have the actual-outcome class applied to it by JS, so it and it alone is displayed:
div.actual-outcome {display: block;}
When the user hits some other link to a span in a possible-outcome div, then that div will become the only one visible (until the user hits a link that isn't to one of those spans).
Here is some sample code:
div.non-actual-outcome {
display: none;
}
div.actual-outcome {
display: block;
}
<div>
<ul>
<li>Turn left</li>
<li>Turn right</li>
</ul>
</div>
<div class="possible-outcome">
<span id="turn-left"></span>
<p>You step into a puddle.</p>
</div>
<div class="possible-outcome">
<span id="turn-right"></span>
<p>You fall into a ditch.</p>
</div>
What is the simplest way to achieve this (and the correct terms in which to ask the question)?
First, add a common class to all your a elements so that they can be distinguished, for example class="tab":
<a class="tab" href="#turn-left">Turn left</a>
Second, hide all div elements by default by adding the display:none property to the CSS selector .possible-outcome (which all div elements have):
div.possible-outcome {
display: none;
}
and use only actual-outcome to hide/show the div you want. No need to use two classes for that, just one will do. If the div has the class actual-outcome then it will be shown, if not then it won't (because it has the class possible-outcome).
Third, when a .tab element get clicked, select its target span along with that span's parent and do some logic: if the span exists and its parent is not currently shown (not having the class actual-outcome), then hide the actually shown div (if exists) and show the current span's parent instead.
Note: If you want to show a div by default just add the class actual-outcome to it:
<div class="possible-outcome actual-outcome">
Full code:
document.addEventListener("click", function(ev) {
var target = ev.target; // get the element that has been clicked
if(target.classList.contains("tab")) { // if the clicked element is a .tab element
var span = document.querySelector(target.getAttribute("href")), // then select that .tab's span to show
parent = span.parentElement; // select the parent of that span (perhaps check if the span exists first to not get the "can't access property parentElement of null")
if(span && !parent.classList.contains("actual-outcome")) { // if the span exists and its parent is not currently shown (not having the class "actual-outcome")
var visibleOutcome = document.querySelector(".actual-outcome"); // then select the current shown element (which we know will have the class "actuall-outcome")
if(visibleOutcome) { // if there is one
visibleOutcome.classList.remove("actual-outcome"); // hide it by remove the class "actual-outcome" from its classList
}
parent.classList.add("actual-outcome"); // and show the current span's parent by adding that same old class
}
}
});
div.possible-outcome {
display: none;
}
div.actual-outcome {
display: block;
}
<div>
<ul>
<li><a class="tab" href="#turn-left">Turn left</a></li>
<li><a class="tab" href="#turn-right">Turn right</a></li>
</ul>
</div>
<div class="possible-outcome">
<span id="turn-left"></span>
<p>You step into a puddle.</p>
</div>
<div class="possible-outcome">
<span id="turn-right"></span>
<p>You fall into a ditch.</p>
</div>
Just for completion, the Divio Cloud interactive debugging checklist for deployments is our implementation of the solution to this problem.
It's like a choose your own adventure story in our Sphinx documentation, to help users identify why a deployment may have failed.
It was was developed on the basis of Ibrahim Mahrir's answer:
One of our actual JS experts (i.e. not me) used my working proof-of-concept based on Ibrahim's answer for the final version.
The JavaScript and CSS are both embedded in the page itself.
The HTML structure is largely determined by the output from Sphinx, hence the need to accommodate the arrangement of elements.
This is the best solution I could come up with. This does not modify the structure by adding any other classes than the ones provided.
HTML:
<div>
<ul>
<li>Turn left</li>
<li>Turn right</li>
</ul>
</div>
<div class="possible-outcome">
<span id="turn-left"></span>
<p>You step into a puddle.</p>
</div>
<div class="possible-outcome">
<span id="turn-right"></span>
<p>You fall into a ditch.</p>
</div>
CSS:
div.non-actual-outcome {
display: none;
}
div.actual-outcome {
display: block;
}
JS:
var outcomeDivs = document.getElementsByClassName('possible-outcome') // selects all divs and returns them as an array
var links = document.querySelectorAll('li') // selects all <li> and returns them as array
// This is turn left li, we will hide turn-right when clicking it.
links[0].addEventListener('click', function(){
outcomeDivs[1].classList.add('non-actual-outcome'); // hides turn-right
links[1].style.display = 'none'; // hides other link
});
// This is turn right li, we will hide turn-left when clicking it.
links[1].addEventListener('click', function(){
outcomeDivs[0].classList.add('non-actual-outcome'); // hides turn-left
links[0].style.display = 'none'; // hides other link
});
CodePen

Jquery will not select button after class has been toggled

I have some jquery that will, when a button is clicked, switch a class from a button to a different class (i.e. on click switch class from #testButton from .first to .second with an image toggle to show it works). The first click works well and it toggles the image, but the second click does not do anything. It seems as if it is not recognizing the new class. Here is a fiddle.
https://jsfiddle.net/myfb44yu/
This is the problematic javascript.
$(document).ready(function(){
$('.first').click(function(){
alert('works');
$('#testButton').toggleClass('first', 'second');
});
$('.second').click(function(){
alert("works");
$('#testButton').toggleClass('second', 'first');
});
});
The interesting thing is that it works when I use an alert() to check but not when I try to change an img src.
Your main issue here is a syntax error in regards to your .toggleClass, but seeing as others have addressed that, I'd like to point out that you should consider re-thinking how you apply your listeners - just as good habit moving forward.
An overview of jQuery Event Bindings
Think of the elements on your page as items in a store. You're an employee, and your manager says "Go put a red tag on anything in the toys department", and so you do. The next day, he puts 10 new toys in the toy department, and says to you "Why don't all the toys have red tags on them?" He then moves one of the toys to the clothing section and asks you, "Why does this item have a red tag on it?" It's simple. You put the red tags on anything in the toys department when he told you to do it - things got moved around afterwards.
The toys in this example would be your .first and .second elements.
This is how jQuery event bindings work - they only apply to elements that satisfied the selector at the time the event was initialized.
So, if you do $('.myClass').click();, then put .myClass on five buttons - none of those buttons will call this function, as they didn't have listeners put on them.
Similarly, if you put a listener on an element using class, but then remove the class from that element, it will maintain the bound event.
The Solution
$(document).on("click", ".first", function() { } );
This is known as event delegation.
In continuing with my analogy from before, this would be the equivalent of skipping tagging the items altogether, and instead just deciding whether or not they're a toy when the customer brings them to the cash register.
Instead of putting the listener on specific elements, we've put it on the entire page. By using ".first" as the second parameter (which takes a selector), the function will only be executed if the element has class first.
Hope this helps.
EDIT: As I was typing, JHecht left a good answer that points out the same issue I outlined above.
N number of elements can have the same class name ,so that's the reason if your trying to search it as $('.classname') returns an array ,so that's the reason your code is not working.class selector
Id is unique,each element should have a single id . In your code button has two id's and for the same button your trying to toggle first and second,you need not have two separate events for first and second
instead you can write as following
check this snippet
$(document).ready(function() {
var firstElements = $('.first')
var first = firstElements[0];
var secondElements = $('.second');
var second = secondElements[0]
$("#testButton").click(function() {
alert('works');
$(this).toggleClass('first').toggleClass('second');
});
});
.first {
color: red;
}
.second {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='first'>Hi</button>
</div>
Hope it helps
Ho about this solution. Hope it helps!
$(document).ready(function(){
$("#testButton").click(function(){
if($(this).prop("class") === "first"){
alert('first');
$(this).removeClass("first").addClass("second");
}
else if($(this).prop("class") === "second"){
alert("second");
$(this).removeClass("second").addClass("first");
}
});
});
.first{
color: red;
}
.second{
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='first'>Hi</button>
</div>
I hope that what I am about to say makes more sense than I feel it does.
Your issue is that when you assign the click events, there is not currently an element that has a class of .second.
Also, your code is wrong. toggleClass accepts a few arguments, the first is a string of classes, the second is an optional parameter to check whether or not to toggle the classes on or off.
A way to accomplish what you want without changing a whole lot of code is event delegation, shown below.
$(function() {
$(document).on('click', '.btn-first,.btn-second', function() {
//here we are adding the click event on the document object, and telling it that we only want to delegate this event to an object that matches the classes of .btn-first or .btn-second.
//Note: to those saying "why not just do it on the .btn class an avoid having to do this", it is so he can see what delegation looks like. But you are correct, with this markup it would be better to simply add the click event on the .btn class.
$(this).toggleClass('btn-first btn-second');
});
});
.btn {
padding: 4px 8px;
border-radius: 3px;
border: 1px solid grey;
}
.btn-first {
background-color: green;
border-color: green;
}
.btn-second {
background-color: orange;
border-color: orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='btn btn-first'>Hi</button>
</div>
A combination of javascript, CSS and HTML to toggle the class of #testButton when any element of class "first" or "second" is clicked, including the test button itself. The posted code was changed to supply JQuery's .toggleClass method with a space separated list of class names. Click "run snippet" to test the effect.
$(document).ready(function(){
$('.first').click(function(){
$('#testButton').toggleClass('first second');
});
$('.second').click(function(){
$('#testButton').toggleClass('first second');
});
});
.first { border: thick outset green;}
.second { border: thick inset red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="first">This paragraph has first class</p>
<p class="second">This paragraph has second class</p>
<button type="button" id="testButton" class="first">this button starts out first class</div>
The script can then be simplified by combining multiple class names in a single selector, leaving just:
$(document).ready(function(){
$('.first, .second').click(function(){
$('#testButton').toggleClass('first second');
});
});
Make a neutral class that the buttons both share (.btn).
Then add one of the state classes to each button (.first or .second).
Delegate the click event to the neutral class only ($('.btn').on('click',...).
Then toggle both state classes on this ($(this).toggleClass('first second');)
The images change by CSS, each button has 2 images which alternate between display:none/block according to the button's state class.
There is an example with the images outside of buttons and another example that doesn't toggle classes around.
SNIPPET
$('.btn').on('click', function() {
$(this).toggleClass('first second');
});
/* OR */
$('.alt').on('click', function() {
$('.img').toggle();
});
.first > .one {
display: block;
}
.first > .two {
display: none;
}
.second > .one {
display: none;
}
.second > .two {
display: block;
}
.first + .one {
display: block;
}
.first + .one + .two {
display: none;
}
.second + .one {
display: none;
}
.second + .one + .two {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Use jQuery with CSS</p>
<button class='btn first'>
<img src='http://placehold.it/50x50/000/fff?text=1' class='one'>
<img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
</button>
<button class='btn second'>
<img src='http://placehold.it/50x50/0e0/960?text=1' class='one'>
<img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
</button>
<br/>
<br/>
<button class='btn first'>Toggle</button>
<img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
<img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
<button class='btn second'>Toggle</button>
<img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
<img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
<p>Or use only jQuery no CSS</p>
<img src='http://placehold.it/50x50/0e0/930?text=1' class='img'>
<img src='http://placehold.it/50x50/930/0e0?text=2' class='img' style='display:none'>
<button class='alt' style='display:block;'>Toggle</button>

Adding an image when clicking on a row (<li> tag)

To solve this problem, i had the idea to create a css class to add the image and when i click on "li", i add the class to it. But for some reason, it just doesnt work. The row appear properly in the ui-grid, but when i click on it, the image doesnt appear. I already tested the onclick() event with an alert() and the function is called.
Since i begin in these languages, i just feel like im assuming things (for exemple, does $(this) really refer to the "li" tag?). If anyone have an idea, it would be appreciated. Here is my code :
CSS
checked
{
background: url('images/checked.png') no-repeat right scroll;
list-style: none;
}
JS
function isChecked()
{
alert("test");
$(this).addClass("checked");
}
HTML
<li class="addedParts" onclick="isChecked()">
<a href="javascript:addParts();">
<div class="ui-grid-solo">
<div class="ui-block-a">test</div>
</div>
</a>
</li>
this will refer to window in your example as context is not passed.
Try this:
function isChecked(elem) {
$(elem).addClass("checked");
}
.checked {
background: url('images/checked.png') no-repeat right scroll;
list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="addedParts" onclick="isChecked(this)">
<a>
<div class="ui-grid-solo">
<div class="ui-block-a">test</div>
</div>
</a>
</li>

How can i make buttons on a HTML page show different information

i am making an information website for a school assignment, i want to have a button/s to make different information display on the page. how do i go about doing this in HTML or other applicable languages, Thanks
Use JavaScript!
<body>
<input id="button1" type="button" value="click me">
<input id="button2" type="button" value="click me, too">
<p id="output"></p>
<script>
/* Get references to your elements. */
var button1=document.getElementById("button1");
var button2=document.getElementById("button2");
var output=document.getElementById("output");
/* Add click event listeners to your buttons so you can interact with them. */
button1.addEventListener("click",clickButton1);
button2.addEventListener("click",clickButton2);
/* Write functions to handle displaying various content depending on which button you press. */
function clickButton1(event_){
output.innerHTML="You clicked button1!";
}
function clickButton2(event_){
output.innerHTML="You clicked button2!";
}
</script>
</body>
Basically, your click event listeners handle what to display when a button is pressed. I'm just changing the text in a p element, but you could do a lot more than that. For example, store the different html you want to display in hidden divs and only display them when a button is pressed. Hope this helps!
I believe you could do this in CSS as well, the big thing to note in the example is that each <a> has the #(id of div) in the href attribute. Since I don't know the exact context for your predicament, I can't say this would work how you want it to, but I just really dislike using javascript if I don't have to.
.container > div {
display: none
}
.container > div:target {
display: block;
}
ul.nav {
list-style-type: none;
}
ul li {
display: inline-block;
width: 100px;
}
ul li button {
border: 1px solid grey;
border-radius: 2px;
padding-left: 5px;
box-sizing: padding-box;
}
<ul class="nav">
<li>
<button>Tab 1
</button>
</li>
<li>
<button>Tab 2
</button>
</li>
<li>
<button>Tab 3
</button>
</li>
<li>
<button>Tab 4
</button>
</li>
<li>
<button>Tab 5
</button>
</li>
</ul>
<div class="container">
<div id="firstTab">Hello Tab 1</div>
<div id="secondTab">Hello Tab 2</div>
<div id="thirdTab">Hello Tab 3</div>
<div id="fourthTab">Hello Tab 4</div>
<div id="fifthTab">Hello Fifth Tab</div>
</div>

how to hide images in a specific list and make them visible in a other list

I have a question: is it possible to hide some images and make the same visible in another list? Here is the code:
<section>
<ul class="portfolio_filters">
<li>show all</li>
<li>New Logos</li>
<!--lightbox2-->
<li>Black & White</li>
<!--lightbox3-->
<li>Industrial</li>
<!--lightbox3-->
<li>Mix</li>
<!--lightbox4-->
</ul>
</section>
i want some images not to show in the "SHOW ALL" list, but if I click (for example) on the black and white list the same image needs to be visible.
thanks for the answers here is for example a linked image
<div class="new col-sm-4 col-md-4">
<div class="portfolio_item"> <a href="images/portfolio/stimson.jpg" class="lightbox"> <img src="images/portfolio/stimson.jpg" alt="Wedding photograph">
<div class="overlay">
<div class="desc">
<h4>Stimson</h4>
<span class="cross"></span> </div>
</div>
</a> </div>
</div>
how to make this visible only in the " NEW LOGOS " list and not in the "SHOW All" list?
You could try something like this:
$("img").hide();
$("li a").click(function(event){
event.preventDefault();
$("img").hide();
filter = $(this).data("filter");
if(filter=="*")
$("img:not(.black)").show();
else
$(filter).show();
});
Demo JsFiddle
Add a class like .hidefromall to the images you want to hide, and use a :not() selector:
<li>show all</li>
It's kinda hard with not all of the code. I assume that all the lists are build the same, and have the same HTML structure.
Most simple is to add a class to the specific list in which you want to hide the 'Show all', lets call that class dontShowAll. In your CSS you can then use:
.portfolio_filters.dontShowAll li:first-child { /*note that the classes a written without a space!! */
display: none;
}
If you aren't able to change the HTML structure you can use child selectors:
section:first-child ul li:first-child { /* only from the first list */
section:nth-child(odd) ul li:first-child { /* from all the odd lists */
section:nth-child(3n) ul li:first-child { /* every third */
section:nth-child(4) ul li:first-child { /* only the fourth */
section:nth-child(n + 5) ul li:first-child { /* the fifth and all that follow */

Categories