I have a custom drop down menu, in which I am using to fill a div with the selections when .is(":checked"). The divs are filling correctly, but I am having some trouble figuring out how to remove the selections in the div.
I think the reason I am having troubles is because the div is only filling with the inputs value. I am unsure of how to remove this value from the proposal-type div and then repopulate the drop list with the item removed, when clicking the x icon. So essentially, exactly the opposite as filling it.
Does anyone see what I have to do to remove the values in the proposal-type div, when clicking the x-icon for the drop-item-selected divs and then how to show the input again in the drop down?
Sorry if any of this is unclear. Please ask any questions if you need more clarity.
$( '#proposal-type' ).click( function () {
$( '#proposal-type-drop' ).addClass( 'active' );
} );
$( '.drop-item-input' ).on( 'change', function () {
var proposalVal = "";
var proposalHtml = "";
$( '.drop-item-input' ).each( function () {
if ( $( this ).is( ":checked" ) ) {
proposalVal += $( this ).val();
proposalHtml += '<div class="drop-item-selected"><span class="drop-item-close"></span>' + $( this ).val() + '</div>';
$( this ).closest( 'label' ).fadeOut();
};
$( '#proposal-type' ).val( proposalVal ).html( proposalHtml );
$( '#proposal-type-drop' ).removeClass( 'active' );
} );
//values
var type = $( '.drop-item-input:checked' ).map( function () {
return $( this ).val();
} ).get().join( ', ' );
console.log( type );
} );
//Uncheck/remove
$( '.drop-item-close' ).click( function () {
$( this ).is( ":checked" ) === false;
$( this ).closest( 'label' ).fadeIn();
$( this ).closest( '.drop-item-selected' ).fadeOut();
} );
#proposal-type {
border: 1px solid #858585;
height: 20px;
}
#proposal-type-drop {
width: 45%;
height
display: none;
position: absolute;
}
#proposal-type-drop.active {
background: rgba(0, 0, 0, 1);
display: block;
height: auto;
z-index: 1;
}
.drop-item {
color: #FFF;
font-size: .9rem;
padding: 5px;
background: #000;
display: block;
width: 100%;
cursor: pointer;
}
.drop-item-close {
display: inline-block;
background-image: url("https://www.wpclipart.com/signs_symbol/alphabets_numbers/outlined_alphabet/white_capitol/capitol_X_white.png");
background-size: 10px 10px;
background-repeat: no-repeat;
height: 10px;
width: 10px;
margin-right: 10px;
cursor: pointer;
}
.drop-item-input {
display: none;
}
.drop-item-selected {
background: blue;
padding: 5px;
font-size: .9rem;
width: auto;
display: inline-block;
margin: 0 3px;
}
.proposal-text {
width: 95%;
display: block;
height: 6em;
margin: 1.5% 2% 2.5% 2%;
!important
}
#proposal-check {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="proposal-type" name="proposal_type" class="proposal-input" data-text="Make Selection"></div>
<div id="proposal-type-drop">
<label class="drop-item">A<input type="checkbox" class="drop-item-input" value="A"></label>
<label class="drop-item">B<input type="checkbox" class="drop-item-input" value="B"></label>
<label class="drop-item">C<input type="checkbox" class="drop-item-input" value="C"></label>
</div>
Your code was too difficult to understand, so I simplified it a little bit.
converted the input blocks to regular html divs.
converted the checkboxes to spans
on click event, I populated a hidden input array.
disabled inputs won't send data to the server, so I used this as an advantage for this kind of situation.
// click event for selectable proposals, assigned them to document to keep the events after attach/detach
$(document).on("click", ".available-proposals .proposal", function(event) {
// after fadeout
$(this).fadeOut("medium", function() {
// set the new container
var newContainer = $(this).closest(".proposal-container").find(".selected-proposals");
// detach the item and move it to the container of the selected ones
$(this).detach().appendTo(newContainer).fadeIn().css("display", "inline-block");
// remove the disabled attribute, so it can send data
$(this).find("input[type='hidden']").removeAttr("disabled");
});
// remove sub event triggers
event.preventDefault();
});
// click event for the X close labels in the selected proposals
$(document).on("click", ".selected-proposals .proposal .close", function(event) {
// select the main proposal object, because the event sender is the close label.
var $this = $(this).parent(".proposal");
// find the new container (old container which has available items)
var newContainer2 = $this.closest(".proposal-container").find(".available-proposals");
// after fadeout
$this.fadeOut("medium", function() {
// detach the item and move it to the container of the selectable ones
$this.detach().appendTo(newContainer2).fadeIn().css("display", "block");
// add the disabled attribute to the input, so it can't send data to the server
$(this).find("input[type='hidden']").attr("disabled","disabled");
});
// remove sub event triggers.
event.preventDefault();
});
.available-proposals .close {
display: none;
}
.selected-proposals .close {
display: block;
font-size: 11px;
background: #eee;
color: #000;
font-weight: bold;
float: right;
padding: 2px;
border-radius: 10px;
}
.available-proposals .proposal {
background: darkblue;
color: white;
width: 100px;
height: 20px;
display: block;
}
.selected-proposals .proposal {
background: cyan;
color: black;
display: inline-block;
width: 100px;
height: 20px;
border: 1px solid black;
padding: 3px;
margin: 3px;
}
.available-proposals {}
.selected-proposals {
border: 1px solid black;
min-height: 20px;
position: relative;
}
.selected-proposals .proposal {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="proposal-container">
<div class="selected-proposals"></div>
<div class="available-proposals">
<div class="proposal">A<span class="close">X</span>
<input type="hidden" name="selected_proposals[]" value="A" disabled="disabled" />
</div>
<div class="proposal" data-value="B">B<span class="close">X</span>
<input type="hidden" name="selected_proposals[]" value="B" disabled="disabled" />
</div>
<div class="proposal" data-value="C">C<span class="close">X</span>
<input type="hidden" name="selected_proposals[]" value="C" disabled="disabled" />
</div>
</div>
</div>
Related
I have a drop down menu I need to make appear and disappear using pure JavaScript (no libraries/jQuery). Thus I am developing a toggle function. However despite trying several approaches, nothing seems to work. My current idea is to create a variable to hold the state of the menu (open or closed). Once the display of the menu changes from "none" to "block", the variable should change from "closed" to "open". Then an event listener would be added to the body element so when anything is clicked, the menu closes (i.e. the display property is changed back to "none").
Unfortunately the above doesn't seem work. When I put the If/else block outside of an event listener it fires when the page loads, but not when the menuToggle variable changes. If I put it or a function inside the menuPlaceholder event listener the menu won't open, probably due to the open and close code being called basically at the same time.
Clearly I am missing something, probably related to program control or function calling. Does anyone have any insights?
The code I am working with is below. Note the alert functions peppered throughout the code are for testing purposes only.
//Puts IDs for search preference selection box into variables
var menuPlaceholder = document.getElementById('searchSelection');
var menuDisplay = document.getElementById('searchOptions');
var boxLabel = document.getElementById('searchLabel');
//Puts IDs for text input box and submission into variables
var searchBoxPlaceholder = document.getElementById('searchInput');
var searchInput = document.getElementById('searchBox');
var submitButton = document.getElementById('submit');
//Adds class to each search option and puts ID of hidde field into variable
var searchPrefSubmission = document.getElementsByClassName('buttonSearch');
var hiddenInput = document.getElementById('searchChoice');
//Global variable to indicate whether searchOptions menu is opened or closed
var menuToggle = "closed";
//Closes element when one clicks outside of it.
function hideOnClickOutside(element) {
const outsideClickListener = event => {
if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
element.style.display = 'none'
removeClickListener()
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length )
//When the placeholder box is clicked, the option menu appears
menuPlaceholder.addEventListener('click', function (event){
menuDisplay.style.display = "block";
menuToggle = "open";
//Add click event to searchPref buttons
for (i = 0; i < searchPrefSubmission.length; i++) {
//Assigns value of the button to both the hidden input field and the placeholder box
searchPrefSubmission[i].addEventListener('click', function(event) {
hiddenInput.value=this.value;
boxLabel.innerHTML = this.value;
menuDisplay.style.display = "none";
menuPlaceholder.style.display = "inline-block";
});
}
});
//This code causes the text input box of the search form to appear when the background box is clicked
searchBoxPlaceholder.addEventListener('click', function(event){
searchInput.style.display = "inline";
submitButton.style.display = "inline";
//hideOnClickOutside(menuDisplay);
});
if (menuToggle == "open"){
document.body.addEventListener('click', function(event){
alert('Foo!');
})
}else{
alert('Boo!');
}
/*function toggleMenu () {
//menuDisplay.style.display = "none";
alert('Boo!');
menuToggle = "closed";
}*/
body {
font-family:Montserrat, sans-serif;
}
#searchOptionPlaceholder {
display: inline-block;
}
#searchSelection {
padding: 10px 20px;
margin-right: 10px;
background-color: #F0F3F5;
display: inline-block;
color: #000000;
width: 140px;
max-width: 200px;
max-height: 35px;
border: 2px solid black;
vertical-align: middle;
}
#searchSelection img {
float: right;
}
#searchLabel {
display: inline-block;
padding-top: 10px;
vertical-align: top;
}
#searchOptions {
display: none;
background-color: #F0F3F5;
position: absolute;
z-index: 2;
}
#searchOptions ul {
background-color: #F0F3F5;
padding: 5px;
}
#searchOptions li {
list-style-type: none;
border-bottom: 2px solid black;
}
#searchOptions li:hover {
background-color: #706868;
color: #ffffff;
}
.buttonSearch {
background-color: transparent;
border: none;
padding: 10px;
font-size: 14px;
}
.searchSubHeading {
font-size: 12px;
}
#searchInput {
display: inline-block;
background-color: #F0F3F5;
padding: 10px 100px;
position: relative;
top: 0px;
max-width: 350px;
border: 2px solid black;
vertical-align: middle;
}
#searchInput img {
position: relative;
left: 80px;
}
#searchBox {
display: none;
width: 80%;
background-color: #F0F3F5;
border: none;
font-size: 1.5em;
position: relative;
right: 50px;
vertical-align: middle;
}
#submit {
border: none;
background-image: url('https://library.domains.skidmore.edu/search/magnifyingGlass.png');
background-repeat: no-repeat;
background-size: contain;
width: 50px;
height: 30px;
position: relative;
right: -80px;
vertical-align: middle;
}
#otherLinks {
margin-top: 10px;
}
#otherLinks a{
color: #000000;
}
#otherLinks a:hover{
color: #006a52;
}
<h1>Library Search</h1>
<form method="post" action="https://library.domains.skidmore.edu/search/searchBox.php" id="librarySearch">
<div id="searchSelection"><span id="searchLabel">Catalog</span><img src="down.png" height="30px" width="30px" /></div>
<div id="searchOptions">
<ul>
<li><button type="button" name="searchPref" value="Catalog" class="buttonSearch">Catalog<br /><br /><span class="searchSubHeading">Search books and DVDs</span></button></li>
<li><button type="button" name="searchPref" value="SearchMore" class="buttonSearch">SearchMore<br /><br /><span class="searchSubHeading">Search everything</span></button></li>
<li><button type="button" name="searchPref" value="Journals" class="buttonSearch">Journals<br /><br /><span class="searchSubHeading">Search journals</span></button></li>
</ul>
</div>
<div id="searchInput">
<input type="hidden" id="searchChoice" name="searchPref" value="catalog" />
<input type="search" id="searchBox" size="60" name="searchText" placeholder="Search our holdings"/><button type="submit" id="submit"></button></div>
<div id="otherLinks">Advanced Catalog Search | WorldCat | eBooks</div>
</form>
Some issues:
Adding event listeners within an event listener is in most cases a code smell: this will add those inner listeners each time the outer event is triggered. Those listeners remain attached, and so they accumulate. So, attach all event handlers in the top-level script, i.e. on page load, and then never again.
The if ... else at the end will execute on page load, and then never again. So the value of menuToggle is guaranteed to be "closed". You need to put that if...else switch inside the handler, so that it executes every time the event triggers, at which time the menuToggle variable will possibly have a modified value.
The body element does not stretch (by default) over the whole window. If you want to detect a click anywhere on the page, you should attach the listener on the document element itself, not on document.body.
When the click on the menu placeholder is handled, you should avoid that this event "bubbles" up the DOM tree up to the document, because there you have the other handler that wants to hide the menu again. You can do this with event.stopPropagation().
The global variable is not absolutely necessary, but if you use it, then I would call it menuVisible and give it a boolean value: false at first, and possibly true later.
For actually toggling the menu, I would create a function, which takes the desired visibility (false or true) as argument, and then performs the toggle.
Do not use undeclared variables, like the for loop variable i. Define it with let.
Here is your code with those changes implemented. Of course, there is still a lot that could be improved, but I believe that goes beyond the scope of this question:
var menuPlaceholder = document.getElementById('searchSelection');
var menuDisplay = document.getElementById('searchOptions');
var boxLabel = document.getElementById('searchLabel');
var searchBoxPlaceholder = document.getElementById('searchInput');
var searchInput = document.getElementById('searchBox');
var submitButton = document.getElementById('submit');
var searchPrefSubmission = document.getElementsByClassName('buttonSearch');
var hiddenInput = document.getElementById('searchChoice');
// Changed name and type of global variable:
var menuVisible = false;
// Removed some functions ...
menuPlaceholder.addEventListener('click', function (event){
// Use new function for actually setting the visibility
toggleMenu(!menuVisible);
// Avoid that click event bubbles up to the document level
event.stopPropagation();
});
// Add these event handlers on page load, not within another handler
// Define loop variable with let
for (let i = 0; i < searchPrefSubmission.length; i++) {
//Assigns value of the button to both the hidden input field and the placeholder box
searchPrefSubmission[i].addEventListener('click', function(event) {
hiddenInput.value = this.value;
boxLabel.innerHTML = this.value;
// Use the new function for setting the visibility
toggleMenu(false);
menuPlaceholder.style.display = "inline-block";
});
}
searchBoxPlaceholder.addEventListener('click', function(event){
searchInput.style.display = "inline";
submitButton.style.display = "inline";
});
// Bind handler on document itself, and call new function
document.addEventListener('click', function(event) {
toggleMenu(false);
});
// new function to perform the toggle
function toggleMenu(show) {
menuDisplay.style.display = show ? "block" : "none";
menuVisible = show;
}
body {
font-family:Montserrat, sans-serif;
}
#searchOptionPlaceholder {
display: inline-block;
}
#searchSelection {
padding: 10px 20px;
margin-right: 10px;
background-color: #F0F3F5;
display: inline-block;
color: #000000;
width: 140px;
max-width: 200px;
max-height: 35px;
border: 2px solid black;
vertical-align: middle;
}
#searchSelection img {
float: right;
}
#searchLabel {
display: inline-block;
padding-top: 10px;
vertical-align: top;
}
#searchOptions {
display: none;
background-color: #F0F3F5;
position: absolute;
z-index: 2;
}
#searchOptions ul {
background-color: #F0F3F5;
padding: 5px;
}
#searchOptions li {
list-style-type: none;
border-bottom: 2px solid black;
}
#searchOptions li:hover {
background-color: #706868;
color: #ffffff;
}
.buttonSearch {
background-color: transparent;
border: none;
padding: 10px;
font-size: 14px;
}
.searchSubHeading {
font-size: 12px;
}
#searchInput {
display: inline-block;
background-color: #F0F3F5;
padding: 10px 100px;
position: relative;
top: 0px;
max-width: 350px;
border: 2px solid black;
vertical-align: middle;
}
#searchInput img {
position: relative;
left: 80px;
}
#searchBox {
display: none;
width: 80%;
background-color: #F0F3F5;
border: none;
font-size: 1.5em;
position: relative;
right: 50px;
vertical-align: middle;
}
#submit {
border: none;
background-image: url('https://library.domains.skidmore.edu/search/magnifyingGlass.png');
background-repeat: no-repeat;
background-size: contain;
width: 50px;
height: 30px;
position: relative;
right: -80px;
vertical-align: middle;
}
#otherLinks {
margin-top: 10px;
}
#otherLinks a{
color: #000000;
}
#otherLinks a:hover{
color: #006a52;
}
<h1>Library Search</h1>
<form method="post" action="https://library.domains.skidmore.edu/search/searchBox.php" id="librarySearch">
<div id="searchSelection">
<span id="searchLabel">Catalog</span>
<img src="down.png" height="30px" width="30px" />
</div>
<div id="searchOptions">
<ul>
<li>
<button type="button" name="searchPref" value="Catalog" class="buttonSearch">
Catalog<br /><br /><span class="searchSubHeading">Search books and DVDs</span>
</button>
</li>
<li>
<button type="button" name="searchPref" value="SearchMore" class="buttonSearch">
SearchMore<br /><br /><span class="searchSubHeading">Search everything</span>
</button>
</li>
<li>
<button type="button" name="searchPref" value="Journals" class="buttonSearch">
Journals<br /><br /><span class="searchSubHeading">Search journals</span>
</button>
</li>
</ul>
</div>
<div id="searchInput">
<input type="hidden" id="searchChoice" name="searchPref" value="catalog" />
<input type="search" id="searchBox" size="60" name="searchText" placeholder="Search our holdings"/>
<button type="submit" id="submit"></button>
</div>
<div id="otherLinks">
Advanced Catalog Search |
WorldCat |
eBooks
</div>
</form>
Description: I created two buttons and two more elements (div & section).
When I click on button 1, div element will appear with background-color HotPink and/if at this moment i re-click on button 1, div element will disappear.
I also wrote a function for button 2 so that when i click on button 2, section element will appear with background-colour DarkGreen and at this moment when i click on button 2 again, section element will disappear.
I should mention that if i click on white space of body ( (document).click(event) ), both div and section elements will disapear.
Question: What function should I write to show div element when I click on button 1 and then I hide hide it when I click on button 2 or any other elements on my web page???
Demo
NOTE: I duplicated this question because I'm not interested to use any method like:
$(".button1").click(function(event){
event.stopPropagation();
if($(".div").css("display") == "none"){
$(".div").css("display","block");
$(".section").css("display","none");
}else{
$(".div").css("display","none");
}
});
$(".button2").click(function(event){
event.stopPropagation();
if($(".section").css("display") == "none"){
$(".section").css("display","block");
$(".div").css("display","none");
}else{
$(".section").css("display","none");
}
});
It would be better if you do a favour and suggest a better method instead of duplicating a line of code with different class name under different events (functions).
My codes:
HTML:
<button class="button1">
Show Div Element
</button>
<div class="div">
I am Div Element
</div>
<br><br>
<button class="button2">
Show Section Element
</button>
<section class="section">
I am Section Element
</section>
JQuery:
$(function(){
$(".button1").click(function(event){
event.stopPropagation();
if($(".div").css("display") == "none"){
$(".div").css("display","block");
}else{
$(".div").css("display","none");
}
});
$(".button2").click(function(event){
event.stopPropagation();
if($(".section").css("display") == "none"){
$(".section").css("display","block");
}else{
$(".section").css("display","none");
}
});
$(document).click(function(){
$(".div").css("display","none");
$(".section").css("display","none");
});
});
The easiest way would be to start .click functions for both button 1 & 2 with:
.css("display","none");
function hidding the other element, like this:
$(".button1").click(function(event){
$(".section").css("display","none");
event.stopPropagation();
if($(".div").css("display") == "none"){
$(".div").css("display","block");
}else{
$(".div").css("display","none");
}
});
$(".button2").click(function(event){
$(".div").css("display","none");
event.stopPropagation();
if($(".section").css("display") == "none"){
$(".section").css("display","block");
}else{
$(".section").css("display","none");
}
});
Solution without JQuery... But you can use it if you really want to.
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
$('.button1').addEventListener('click', ()=>{
toggle('div')
});
$('.button2').addEventListener('click', ()=>{
toggle('section')
});
function toggle(element){
if($('.show')){
Array.from($$('.show')).forEach((ele) => {
ele.classList.remove('show');
});
}
$(element).classList.add('show');
}
html, body {
background-color: #fafafa;
width: 100%;
height: 100%;
padding: 12px;
margin: 0;
}
.button1 {
background-color: pink;
position: relative;
display: inline-block;
padding: 8px;
border: none;
margin: 0 0 6px 0;
cursor: pointer;
}
.div {
background-color: hotpink;
display: none;
width: 160px;
height: 160px;
}
.button2 {
background-color: green;
position: relative;
display: inline-block;
padding: 8px;
color: white;
border: none;
margin: 0 0 6px 0;
cursor: pointer;
}
.section {
background-color: darkgreen;
display: none;
width: 160px;
height: 160px;
color: white;
}
.show {
display: block;
}
<button class="button1">
Show Div Element
</button>
<div class="div">
I am Div Element
</div>
<br>
<br>
<button class="button2">
Show Section Element
</button>
<section class="section">
I am Section Element
</section>
This solution relies on event bubbling, so it might break if other handlers stop propagation.
Also note that it currently relies on provided html structure, but that can be tweaked easy enough.
$(document).click(function(e) {
$elem = $(e.target)
// If the element is visible we shouldn't open it again
needToggle = $elem.is('button') && !$elem.next().hasClass("open")
$(".open").removeClass("open") // Remove all open elements
if (needToggle) {
$elem.next().toggleClass("open")
}
})
html,
body {
background-color: #fafafa;
width: 100%;
height: 100%;
padding: 12px;
margin: 0;
}
.button1 {
background-color: pink;
position: relative;
display: inline-block;
padding: 8px;
border: none;
margin: 0 0 6px 0;
cursor: pointer;
}
.div {
background-color: hotpink;
display: none;
width: 160px;
height: 160px;
}
.button2 {
background-color: green;
position: relative;
display: inline-block;
padding: 8px;
color: white;
border: none;
margin: 0 0 6px 0;
cursor: pointer;
}
.section {
background-color: darkgreen;
display: none;
width: 160px;
height: 160px;
color: white;
}
.open {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button1">
Show Div Element
</button>
<div class="div">
I am Div Element
</div>
<br><br>
<button class="button2">
Show Section Element
</button>
<section class="section">
I am Section Element
</section>
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I am working on a project and there I am getting a value from input tag and then insert input value in a div and appending on screen with children element.
And What I want that when user click on children element then parent div would be removed and for this I'm using a function. That is working when I am using by default a section but when I append a section and then click on that's children where a function call like when user click on it's children parent section would be removed but my functionality not working.
$('#btn').click(function() {
var menuFieldName = $('#text').val();
$('.div').append('<div class="a">' + menuFieldName + '<span>X</span></div>');
$('#text').val('');
});
$('.div .a span').on('click', function() {
$(this).parent().remove();
});
.a {
display: inline-block;
padding: 5px 35px 5px 10px;
position: relative;
background: #eee;
border-radius: 20px;
margin: 10px;
}
.a span {
position: absolute;
top: 0;
right: 0;
background: #333;
color: #fff;
height: 28px;
width: 28px;
text-align: center;
line-height: 28px;
border-radius: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
<div class="a">Test <span>X</span></div>
</div>
<input type="text" id="text">
<button id="btn">Add</button>
https://jsfiddle.net/jafaruddeen/rag71ma0/
You are appending elements dynamically but you are not attaching any event handler to the newly added elements. To solve this you can use event delegation, you can attach events to .div like $('.div').on('click', '.a span', function() {
$('#btn').click(function() {
var menuFieldName = $('#text').val();
$('.div').append('<div class="a">' + menuFieldName + '<span>X</span></div>');
$('#text').val('');
});
$('.div').on('click', '.a span', function() {
$(this).parent().remove();
});
.a {
display: inline-block;
padding: 5px 35px 5px 10px;
position: relative;
background: #eee;
border-radius: 20px;
margin: 10px;
}
.a span {
position: absolute;
top: 0;
right: 0;
background: #333;
color: #fff;
height: 28px;
width: 28px;
text-align: center;
line-height: 28px;
border-radius: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
<div class="a">Test <span>X</span></div>
</div>
<input type="text" id="text">
<button id="btn">Add</button>
The reason you can't remove it is because when you register the event, the element on which you try to register it doesn't exist yet.
You need to use event delegation
$('body').on('click', '#my-element', function(){...});
you have to call click function after append.. or call click function globally(body element) and match the span..
$(document).ready(function(){
$('#btn').on('click',function(){
var menuFieldName = $('#text').val();
$('.div').append('<div class="a">'+menuFieldName+'<span class="close">X</span></div>');
$('.div .a span').on('click', a);
$('#text').val('');
});
$('.div .a span').on('click', a);
function a() {
$(this).parent().remove();
}
});
check your js fiddle. fixed it -> https://jsfiddle.net/jafaruddeen/rag71ma0/
Does anybody know why the button wont react to input when clicked? I want the click to bring up a prompt and then use the text from the prompt and append it into the hmtl as a list item with the same css as the other list items.
$(".btn").click(function() {
var text = prompt('What do you need to do?')
var txt1 = $("<li id="
listItem "><p></p></li>").text(text);
$("#itemList").append(txt1);
});
body {
background: #bff0ff;
}
li {
display: inline-block;
float: left;
padding: 5px;
}
#list {
list-style-type: none;
}
#itemList {
list-style-type: none;
}
#listItem {
width: 250px;
height: 75px;
border-radius: 5px;
background: #5ABCB9;
}
#listItem p {
font-family: curive, sans-serif;
text-align: center;
font-size: 20px;
color: #
}
.btn {
height: 50px;
width: 50px;
border-radius: 50%;
border: 1px;
font-size: 40px;
background: #63E2C6;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<input type="button" class="btn" value="+" />
<ul id="itemList">
<li id="listItem">
<p>
Study for exams.
</p>
</li>
</ul>
If you are trying to add more li elements to your existing ul, try the following ( since with your current implementation p element would be ignored when rendered ) :
$(".btn").click(function() {
var text = prompt('What do you need to do?')
var $li = $('<li/>',{ 'class' : 'listItem' })
var $p = $('<p/>', { 'text' : text })
$($li).append($p);
$("#itemList").append($li);
});
Example : https://jsfiddle.net/9av0c8z3/
There's a few things you need to do. First of those should be to clean up the errors in your JS, i.e. this isn't a proper string:
"<li id="listItem"><p></p></li>"
Once you hit the second double quote (") you're no longer working with a string and it thinks listItem is a variable.
I personally use single quotes for strings (').
'<li id="listItem"><p></p></li>'
Then you'll have to redo how you're using IDs in CSS. IDs should be unique and not re-used, that's what a class is for. So I've changed instances of id="listItem" to class="listItem" and updated the CSS from #listItem to .listItem.
Also, when you do this $( '<li id="listItem"><p></p></li>' ).text( text ); the text gets added to the li and the p is not created. So create the p first, add the text to it then append it to the li.
After that I think you're good to go.
var $itemList = $( '#itemList' );
$( '.btn' ).click( function( e ) {
var text = prompt( 'What do you need to do?' ),
p = $( '<p>', { text: text } ),
li = $( '<li>', { "class": 'listItem' } ).append( p );
$itemList.append( li );
} );
body {
background: #bff0ff;
}
#itemList,
#itemList li {
list-style: none;
}
li {
float: left;
padding: 5px;
}
.listItem {
width: 250px;
height: 75px;
border-radius: 5px;
background: #5ABCB9;
}
.listItem p {
font-family: curive, sans-serif;
text-align: center;
font-size: 20px;
}
.btn {
height: 50px;
width: 50px;
border-radius: 50%;
border: 1px;
font-size: 40px;
background: #63E2C6;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<input type="button" class="btn" value="+">
<ul id="itemList">
<li class="listItem">
<p>
Study for exams.
</p>
</li>
</ul>
I'm trying for about 2 hours now to get something so simple done but there seems to be something in the way that blocks my function from working, I don't understand what causing the function not to work and how can I get it to show the icons change on a click.
any help would be much appreciated, please see the link below, resize your browser a bit so you will see the menu toggle.
I am trying to change the div class to menu-close and not menu-toggle on click so there will be a different icon.
here is the link to see it on the website:
http://didyouknowfacts.org/animals/
here is my html + javascript:
<nav id="site-navigation" class="main-navigation" role="navigation">
<div class="col-width">
<script>
$(function() {
$( "#openclose" ).click(function(){
$( ".menu-toggle" ).switchClass( "menu-toggle", "menu-close", 1000 );
$( ".menu-close" ).switchClass( "menu-close", "menu-toggle", 1000 );
});
});
</script>
<div id="openclose" class="menu-toggle"><?php _e( 'Menu', 'theme-name' ); ?></div>
<a class="skip-link screen-reader-text" href="#content"><?php _e( 'Skip to content', 'theme-name' ); ?></a>
</div>
<?php wp_nav_menu( array('theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?>
</div>
</nav><!-- #site-navigation -->
here is the css:
.menu-toggle {
cursor: pointer;
font-size: 0;
margin: 0;
overflow: hidden;
position: absolute;
top: 17px;
right: 10px;
text-align: center;
}
.menu-toggle:before {
-webkit-font-smoothing: antialiased;
display: inline-block;
font: normal 30px/1 FontAwesome;
text-decoration: inherit;
vertical-align: text-bottom;
color: #fff;
content: "\f0c9";
margin: 0;
}
.menu-close {
cursor: pointer;
font-size: 0;
margin: 0;
overflow: hidden;
position: absolute;
top: 17px;
right: 10px;
text-align: center;
}
.menu-close:before {
-webkit-font-smoothing: antialiased;
display: inline-block;
font: normal 30px/1 FontAwesome;
text-decoration: inherit;
vertical-align: text-bottom;
color: #fff;
content: "\f00d";
margin: 0;
}
What I bet is happening is that when you frist write this
$( ".menu-toggle" ).switchClass( "menu-toggle", "menu-close", 1000 );
all .menu-toggle objects "switch" into menu-close objects, meaning you only have a bunch of .menu-close objects in your dom. And when you later then write this:
$( ".menu-close" ).switchClass( "menu-close", "menu-toggle", 1000 );
all you .menu-close objects turn into .menu-toggle, meaning all your objects are now .menu-close.
Therefore we just change your click function to inluce a pointer to the currently clicked menu item.
$( "#openclose" ).click(function(){ //If this is not a unique name then it should by the way be a class, not an id.
$( ".menu-toggle" ).switchClass( "menu-toggle", "menu-close", 1000 );
$( this ).switchClass( "menu-close", "menu-toggle", 1000 })
})
If I go to your web page, I see the error "Uncaught ReferenceError: $ is not defined". jquery is defined below your script, so $(function() ... does not get executed at all.
Try using the addClass() and removeClass(). If you want to toggle it, you can use if else statements.
$(document).ready(function(){
$("button").click(function(){
$('.blue').addClass('orange');
$('.orange').removeClass('blue');
$('div').animate({borderRadius: "100px"})
});
});
.blue{
height: 150px;
width: 150px;
border-radius: 5px;
border: 1px solid black;
background-color: royalblue;
}
.orange{
background-color: orange;
height: 150px;
width: 150px;
border-radius: 5px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='blue'></div>
<button> Change Color</button>