I was playing around jQuery and wanted to add div element with append but it doesn't seem to work, it does absolutely nothing when I click on button.
$(document).ready(function() {
$('#main').on('click', '#btn', function() {
var value = $('#main input').val();
var html = '<div id="cont4><p>' + value + '</p></div>';
$('#main').append(html);
})
})
#cont4 {
width: 290px;
height: 600px;
background: rgb(30, 33, 33, 0.85);
margin-top: 15vh;
margin-left: 17vh;
border-radius: 25px;
transition: 0.35s;
color: white;
text-align: center;
box-shadow: 5px 10px #0c0921;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<div id="cont1">
<h1>Basic</h1>
<p>Buy <span>Basic</span> packet and get:</p>
<p>300 Minutes Talk</p>
<p>500 SMS</p>
<p>5GB NET More info</p>
<button>Buy Now !</button>
</div>
<input>asd
<button id="btn">add</button>
</div>
You have a small typo error in your code ;).
closing " is missing in your append function
$(document).ready(function() {
$('#main').on('click', '#btn', function() {
var value = $('#main input').val();
var html = '<div id="cont4"><p>' + value + '</p></div>';
$('#main').append(html);
})
})
#main {
background: red;
padding: 10px;
cursor: pointer;
}
#cont4 {
background: green;
padding: 10px;
}
#btn {
background: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="main"><input type="text"></input>This is the main container<button id="btn">Button</button></div>
you missed double quotes for id="cont4" in this line, so use the below line in your js
var html = '<div id="cont4"><p>' + value +'</p></div>';
Working code here
$(document).ready(function() {
$('#main').on('click', '#btn', function() {
var value = $('#main input').val();
var html = '<div id="cont4"><p>' + value + '</p></div>';
$('#main').append(html);
})
})
#cont4 {
width: 290px;
height: 600px;
background: rgb(30, 33, 33, 0.85);
margin-top: 15vh;
margin-left: 17vh;
border-radius: 25px;
transition: 0.35s;
color: white;
text-align: center;
box-shadow: 5px 10px #0c0921;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<div id="cont1">
<h1>Basic</h1>
<p>Buy <span>Basic</span> packet and get:</p>
<p>300 Minutes Talk</p>
<p>500 SMS</p>
<p>5GB NET More info</p>
<button>Buy Now !</button>
</div>
<input>asd
<button id="btn">add</button>
</div>
You need to create a jQuery element for append function.
Change this
'<div id="cont4"><p>' + value +'</p></div>'
to
$('<div id="cont4"><p>' + value +'</p></div>');
that means you are creating a element from that string. then append that to another element.
$(document).ready(function() {
$('#main').on('click', '#btn', function(){
var value = $('#main input').val();
var html = $('<div id="cont4"><p>' + value +'</p></div>');
$('#main').append(html);
})
})
Related
I have just found a set of codes that fits my need right now for my blog.
Here I'll attach the code and a glimpse of what it looks like. Although It's still very simple.
What I want to ask is if it's possible to tweak these code possible using JS localstorage, so that it will keep all the saved text even after the user refresh the page, or even better if it stays there even after a user closed the window and reopened it later?
Here's what it looks like right now
and here is the code:
$(document).ready(function(){
var noteCount = 0;
var activeNote = null;
$('.color-box').click(function(){
var color = $(this).css('background-color');
$('notepad').css('background-color', color);
$('#title-field').css('background-color', color);
$('#body-field').css('background-color', color);
})
$('#btn-save').click(function(){
var title = $('#title-field').val();
var body = $('#body-field').val();
if (title === '' && body === '') {
alert ('Please add a title or body to your note.');
return;
}
var created = new Date();
var color = $('notepad').css('background-color');
var id = noteCount + 1;
if (activeNote) {
$('#' + activeNote)[0].children[0].innerHTML = title;
$('#' + activeNote)[0].children[1].innerHTML = created.toLocaleString("en-US");
$('#' + activeNote)[0].children[2].innerHTML = body;
$('#' + activeNote)[0].style.backgroundColor = color;
activeNote = null;
$('#edit-mode').removeClass('display').addClass('no-display');
} else {
var created = new Date();
$('#listed').append('<div id="note' + id + '" style="background-color: ' + color + '"><div class="list-title">' + title + '</div> <div class="list-date">' + created.toLocaleString("en-US") + '</div> <div class="list-text">' + body + '</div> </div>');
noteCount++;
};
$('#title-field').val('');
$('#body-field').val('');
$('notepad').css('background-color', 'white');
$('#title-field').css('background-color', 'white');
$('#body-field').css('background-color', 'white');
});
$('#btn-delete').click(function(){
if (activeNote) {
$('#' + activeNote)[0].remove();
activeNote = null;
$('#edit-mode').removeClass('display').addClass('no-display');
}
$('#title-field').val('');
$('#body-field').val('');
$('notepad').css('background-color', 'white');
$('#title-field').css('background-color', 'white');
$('#body-field').css('background-color', 'white');
});
$('#listed').click(function(e){
var id = e.target.parentElement.id;
var color = e.target.parentElement.style.backgroundColor;
activeNote = id;
$('#edit-mode').removeClass('no-display').addClass('display');
var titleSel = $('#' + id)[0].children[0].innerHTML;
var bodySel = $('#' + id)[0].children[2].innerHTML;
$('#title-field').val(titleSel);
$('#body-field').val(bodySel);
$('notepad').css('background-color', color);
$('#title-field').css('background-color', color);
$('#body-field').css('background-color', color);
})
})
header {
text-align: left;
font-weight: 800;
font-size: 28px;
border-bottom: solid 3px #DEDEDE;
display: flex;
justify-content: space-between;
}
footer {
display: flex;
flex-flow: row-reverse;
padding: 5px 20px;
}
.headers {
margin-top: 20px;
margin-bottom: -10px;
font-size: 20px;
}
#list-head {
margin-left: 2.5%;
width: 30.5%;
display: inline-block;
text-align: center;
}
#note-head {
width: 60%;
margin-left: 5%;
display: inline-block;
text-align: center;
}
noteList {
margin-top: 20px;
display: inline-block;
margin-left: 2.5%;
width: 30.5%;
height: 400px;
overflow: scroll;
border: solid 3px #929292;
border-radius: 5px;
background-color: #DEDEDE;
}
.within-list {
cursor: pointer;
}
.list-title {
font-weight: 600;
font-size: 20px;
padding: 5px 5px 0 5px;
}
.list-date {
font-weight: 200;
font-style: italic;
font-size: 12px;
padding: 0 5px 0 5px;
}
.list-text {
padding: 0 5px 5px 5px;
border-bottom: solid 1px black;
}
notePad {
display: inline-block;
border: solid 3px black;
border-radius: 10px;
height: 400px;
overflow: scroll;
width: 60%;
margin-left: 5%;
margin-top: 0;
}
#note-title {
font-size: 24px;
padding: 0 0 5px 5px;
border-bottom: solid 2px #DEDEDE;
}
#note-body {
padding: 5px;
}
#body-field, #title-field {
width: 100%;
border: none;
outline: none;
resize: none;
}
#title-field {
font-size: 18px;
font-weight: 600;
}
#body-field {
font-size: 14px;
font-weight: 500;
height: 400px;
}
#color-select {
display: flex;
flex-flow: row-reverse nowrap;
padding: 5px 10px 0 0;
}
.color-box {
border: solid 2px #929292;
height: 10px;
width: 10px;
margin-left: 5px;
}
.display {
display: visible;
}
.no-display {
display: none;
}
button {
margin: 5px;
border: solid 3px grey;
border-radius: 10%;
font-size: 22px;
font-weight: 800;
text-transform: uppercase;
color: #DEDEDE;
}
button:hover, .color-box:hover {
cursor: pointer;
}
#listed:nth-child(odd):hover {
cursor: pointer;
}
#btn-save {
background-color: #2F5032;
}
#btn-delete {
background-color: #E41A36;
}
.white {
background-color: white;
}
.orange {
background-color: #FFD37F;
}
.banana {
background-color: #FFFA81;
}
.honeydew {
background-color: #D5FA80;
}
.flora {
background-color: #78F87F;
}
.aqua {
background-color: #79FBD6;
}
.ice {
background-color: #79FDFE;
}
.sky {
background-color: #7AD6FD;
}
.orchid {
background-color: #7B84FC;
}
.lavendar {
background-color: #D687FC;
}
.pink {
background-color: #FF89FD;
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title></title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
The Note Machine
<div id='color-select'>
<div class='color-box white'></div>
<div class='color-box orange'></div>
<div class='color-box banana'></div>
<div class='color-box honeydew'></div>
<div class='color-box flora'></div>
<div class='color-box aqua'></div>
<div class='color-box ice'></div>
<div class='color-box sky'></div>
<div class='color-box orchid'></div>
<div class='color-box lavendar'></div>
<div class='color-box pink'></div>
</div>
</header>
<main>
<div class="headers">
<div id="list-head">
<b>Your Notes</b> <i>(click to edit/delete)</i>
</div>
<div id="note-head">
<b>Your Notepad</b>
<span id="edit-mode" class="no-display">
<i> (edit mode) </i>
</span>
</div>
</div>
<noteList>
<div id='listed'>
</div>
</noteList>
<notepad>
<div id="note-title">
<input id="title-field" type="text" placeholder="title your note">
</div>
<div id="note-body">
<textarea id="body-field"></textarea>
</div>
</notepad>
</main>
<footer>
<button id="btn-save">Save</button>
<button id="btn-delete">Delete / Clear </button>
</footer>
</body>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script>
<script type='text/javascript' src='app.js'></script>
</html>
I tried searching in the net for other notepads, but they aren't working on my blog, and here's the one that is finally working. I would really appreciate any kind of suggestions and assistance. T
If all you want to do is save to LocalStorage when save is clicked, then it would be as simple as saving the title and body variables to LocalStorage in the $('#btn-save').click() handler.
Assuming that (as #Nawed Khan guessed) you want to have the note saved without the user having to click save, then you'll want to make three changes:
In the main body of your $(document).ready() function, check for existing LocalStorage values, and if they exist, then set them on your $('#title-field') and $('#body-field') elements.
Add two new change handlers to your $('#title-field') and $('#body-field') elements. When these change handlers fire, get the title and body values from the elements and save them to LocalStorage.
In the $('#btn-save').click() and $('#btn-delete').click() handlers, reset the LocalStorage values of the active note.
You should find these links useful:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
https://api.jquery.com/change/
P.S. The information stored in LocalStorage can be lost if the user chooses to clear their browser data. If preservation of the data is vital, then implementing a solution using AJAX to connect to a database as #The Rahul Jha suggested would guarantee preservation of the data.
Yes , You can save the data in localStorage and fetch the data on page load. To set the localStorage item add below function in your script which is setting the item on keyup of textarea in localstorage.
$(document).on("keyup","#body-field",function(){
var text = $("#body-field").val();
localStorage.setItem("savedData", text);
});
Add below method to fetch the data from local storage
function loadDataFromLocalStorage(){
if (localStorage.getItem("savedData") !== null) {
$("#body-field").val(localStorage.getItem("savedData"))
}
}
And at last call the above method in $(document).ready() or page load to set the data back in text area after page load.
Put this inside the $(document).ready block:
$(“#title-field”).val(window.localStorage.getItem(“title”) || “”);
$(“#body-field”).val(window.localStorage.getItem(“body”) || “”);
$(“#title-field, #body-field”).change(function() {
var title = $(“#title-field”).val();
var body = $(“#body-field”).val();
window.localStorage.setItem(“title”, title);
window.localStorage.setItem(“body”, body)
})
The 2 first lines will load the text from the localStorage and sets the data on the corresponding inputs
The rest of the code is the part where the data is being saved to localStorage every time the value of #title-field OR #body-field changes.
can someone take a look at the code here is the problem screenshot
enter image description here
when clicking on sidebar user a popup appears after clicking on popup header it will go down and then if someone will click on the same user from sidebar a duplicate instance is created and click on the head will make the first one appear and 2nd one to go down.
I want to stop that duplication when someone clicks on sidebar user again then the already generated popup will toggle.
https://jsfiddle.net/hamzasgd/Lqyajokp/4/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facebook like chat popup layout</title>
</head>
<body>
<div id="chat-sidebar">
<div id="sidebar-user-box" class="100">
<img src="user.png" />
<span id="slider-username">User 1</span>
</div>
<div id="sidebar-user-box" class="200">
<img src="user.png" />
<span id="slider-username">User 2</span>
</div>
</div>
</body>
</html>
$(document).ready(function(){
var arr = []; // List of users
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel") ;
$('[rel="'+chatbox+'"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel") ;
$('[rel="'+chatbox+'"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text() ;
if ($.inArray(userID, arr) != -1)
{
arr.splice($.inArray(userID, arr), 1);
}
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="'+ userID+'">'+
'<div class="msg_head">'+username +
'<div class="close">x</div> </div>'+
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>'+
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>' ;
$("body").append( chatPopup );
displayChatBox();
});
$(document).on('keypress', 'textarea' , function(e) {
if (e.keyCode == 13 ) {
var msg = $(this).val();
$(this).val('');
if(msg.trim().length != 0){
var chatbox = $(this).parents().parents().parents().attr("rel") ;
$('<div class="msg-right">'+msg+'</div>').insertBefore('[rel="'+chatbox+'"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox(){
i = 270 ; // start position
j = 260; //next position
$.each( arr, function( index, value ) {
if(index < 4){
$('[rel="'+value+'"]').css("right",i);
$('[rel="'+value+'"]').show();
i = i+j;
}
else{
$('[rel="'+value+'"]').hide();
}
});
}
});
I've added a check that will look if you already have a chatbox with that userID:
var exist = $('.msg_box[rel="' + userID + '"]').length;
if (exist == 0) {
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="' + userID + '">' +
'<div class="msg_head">' + username +
'<div class="close">x</div> </div>' +
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>' +
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>';
$("body").append(chatPopup);
displayChatBox();
}
Please note that you have some invalid html. You are not allowed, to have the id on multiple element.
Demo
$(document).ready(function() {
var arr = []; // List of users
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel");
$('[rel="' + chatbox + '"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel");
$('[rel="' + chatbox + '"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text();
if ($.inArray(userID, arr) != -1) {
arr.splice($.inArray(userID, arr), 1);
}
var exist = $('.msg_box[rel="' + userID + '"]').length;
if (exist == 0) {
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="' + userID + '">' +
'<div class="msg_head">' + username +
'<div class="close">x</div> </div>' +
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>' +
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>';
$("body").append(chatPopup);
displayChatBox();
} else {
$('.msg_box[rel="' + userID + '"] .msg_wrap').slideToggle('slow');
}
});
$(document).on('keypress', 'textarea', function(e) {
if (e.keyCode == 13) {
var msg = $(this).val();
$(this).val('');
if (msg.trim().length != 0) {
var chatbox = $(this).parents().parents().parents().attr("rel");
$('<div class="msg-right">' + msg + '</div>').insertBefore('[rel="' + chatbox + '"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox() {
i = 270; // start position
j = 260; //next position
$.each(arr, function(index, value) {
if (index < 4) {
$('[rel="' + value + '"]').css("right", i);
$('[rel="' + value + '"]').show();
i = i + j;
} else {
$('[rel="' + value + '"]').hide();
}
});
}
});
/**** Chat Popup Layout******/
body {
background: #e5e5e5;
font-family: sans-serif;
}
.msg_box {
position: fixed;
bottom: -5px;
width: 250px;
background: white;
border-radius: 5px 5px 0px 0px;
}
.msg_head {
background: black;
color: white;
padding: 8px;
font-weight: bold;
cursor: pointer;
border-radius: 5px 5px 0px 0px;
}
.msg_body {
background: white;
height: 200px;
font-size: 12px;
padding: 15px;
overflow: auto;
overflow-x: hidden;
}
.msg_input {
width: 100%;
height: 55px;
border: 1px solid white;
border-top: 1px solid #DDDDDD;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.close {
float: right;
cursor: pointer;
}
.minimize {
float: right;
cursor: pointer;
padding-right: 5px;
}
.msg-left {
position: relative;
background: #e2e2e2;
padding: 5px;
min-height: 10px;
margin-bottom: 5px;
margin-right: 10px;
border-radius: 5px;
word-break: break-all;
}
.msg-right {
background: #d4e7fa;
padding: 5px;
min-height: 15px;
margin-bottom: 5px;
position: relative;
margin-left: 10px;
border-radius: 5px;
word-break: break-all;
}
/**** Slider Layout Popup *********/
#chat-sidebar {
width: 250px;
position: fixed;
height: 100%;
right: 0px;
top: 0px;
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid #b2b2b2;
}
#sidebar-user-box {
padding: 4px;
margin-bottom: 4px;
font-size: 15px;
font-family: Calibri;
font-weight: bold;
cursor: pointer;
}
#sidebar-user-box:hover {
background-color: #999999;
}
#sidebar-user-box:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
img {
width: 35px;
height: 35px;
border-radius: 50%;
float: left;
}
#slider-username {
float: left;
line-height: 30px;
margin-left: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chat-sidebar">
<div id="sidebar-user-box" class="100">
<img src="user.png" />
<span id="slider-username">User 1</span>
</div>
<div id="sidebar-user-box" class="200">
<img src="user.png" />
<span id="slider-username">User 2</span>
</div>
</div>
I have created a Wikipedia finder web app that accesses the Wikipedia API. However, to append the JSON data to HTML I used the append() function:
$('.results').append('<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>');
The problem is when a user wants to search a new term to search bar. The new results go under the previous results because of the append(). The codepen to my app is https://codepen.io/mrsalami/pen/NwrGjj
You have to clear .result before appending new content, with snippet below
$(document).ready(function(){
$(".button").on("click", function(){
var value = $('#searchItem').val();
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=info%7Cextracts&list=&generator=search&utf8=1&inprop=url&exsentences=2&exintro=1&gsrsearch=" + value + "&gsrlimit=10&origin=*"
$.getJSON(url, function(x) {
var testCheck = x.query.pages;
// Clear the div before appending current result
$('.results').html("");
for (var key in testCheck) {
if (testCheck.hasOwnProperty(key)) {
console.log(testCheck[key].title);
console.log(testCheck[key].fullurl);
console.log(testCheck[key].extract);
$('.results').append('<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>');
}
}
});
});
});
header {
text-align: center;
margin-bottom: 40px;
}
.entryOne {
background-color: white;
border: 6px solid red;
min-height: 90px;
padding: 10px;
margin-bottom: 30px;
}
.linksa {
text-decoration: none !important;
color: black;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<h1>Jafar Wikipedia Search</h1>
<input type="text" name="searchItem" class="searchItem" id="searchItem" placeholder="Search">
<a class="button">Button</a>
</header>
<div class="results"></div>
If you really want JQuery:
$('.results').html('<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>');
or just use vanilla javascript:
document.querySelector(".results").innerHTML = '<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>';
I have the following code which switches between the states of hide() and show() of show prices button.I am aware about .toggle() in jQuery.But I couldn't find a workaround of it in this instance.
When I click the button the <p></p> element is appended to .msg class in the div and when I click it once again it hides it state by removing the <p></p> element from the DOM (which is in the else block).
I have managed to come up with a solution which works well using If..else, yet it doesn't feel right or the best way to do it. I find this solution naive and want to know what I can do to further optimize this code.
Following is the code:
(function() {
//$('.not-interested').hide();
$('.msg').hide();
var showPrice = function(e) {
e.stopPropagation();
var vacation = $(this).closest('.vacation');
var button = vacation.find('button');
if ((!vacation.hasClass('present'))) {
var price = +vacation.data('price');
var vacation_place = vacation.find('h3').text();
var msg = $("<p style='text-align:center;line-height:24px;font-size:13px;'>Price for " + vacation_place + " is: " + (3 * price) + " </p>");
vacation.find('.msg').prepend(msg).show();
vacation.addClass('present');
} else if ((e.type == 'click' && e.toElement.localName == 'button') || e.type == 'showAll') {
//console.log(e.toElement.localName);
//vacation.on('click','button')){
//console.log(e.toElement);
//console.log(vacation.on('click','button').context);
//console.log(button);
vacation.removeClass('present');
vacation.find('.msg').hide().find('p').remove();
}
};
var removePrice = function(e) {
e.stopPropagation();
var vacation = $(this).closest('.vacation');
vacation.find('div.msg').hide();
//vacation.on('click.price','button',showPrice);
};
$('.vacation').on('click.show', 'button', showPrice);
$('.vacation').on('showAll.price', showPrice); // creating a custom event
$('.show-all-price').on('click', function(e) {
e.preventDefault();
$('.vacation').trigger('showAll.price'); // firing a custom event on click of an anchor
});
})();
body,
ul {
font-size: 100%;
margin: 0;
padding: 0;
font-family: "sans-serif";
color: #fff;
}
.show-all {
width: 100px;
background: #597C80;
margin-top: 25px;
margin-left: 25px;
border: 1px solid #2A3F41;
}
.show-all a {
display: block;
text-decoration: none;
color: #333;
text-align: center;
padding: 10px;
font-size: 13px;
}
ul {
list-style: none;
margin-top: 20px;
margin-left: 20px;
float: left;
}
li {
float: left;
display: block;
padding: 10px;
background: #2A3F41;
margin-right: 10px;
padding-bottom: 25px;
}
li h3 {
text-align: center;
}
li > div {
width: 80%;
margin: 0 auto;
}
li button {
width: 100%;
background: #377C37;
color: #333;
border: none;
outline: 0;
cursor: pointer;
padding: 5px 9px;
}
button:active {
position: relative;
top: 2px;
/* padding: 8px 13px 6px;*/
}
li a {
display: block;
margin-top: 10px;
text-align: center;
text-decoration: none;
color: #597C80;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<body>
<div class="show-all">
Show all
</div>
<ul id="vacation-list">
<li class="vacation" data-price="395">
<h3>Hawaiian Vacation</h3>
<div>
<button>Show all prices</button>
<div class="msg">
Not Interested
</div>
</div>
</li>
<li class="vacation" data-price="315">
<h3>American Vacation</h3>
<div>
<button>Show all prices</button>
<div class="msg">
Not Interested
</div>
</div>
</li>
<li class="vacation" data-price="420">
<h3>French Vacation</h3>
<div>
<button>Show all prices</button>
<div class="msg">
Not Interested
</div>
</div>
</li>
</ul>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="js/app.js"></script>
</body>
I've also tried using .on() and .off() with name spacing but couldn't figured how to do it appropriately.
Here's the code with .on() and .off() switching:
(function(){
//$('.not-interested').hide();
$('.msg').hide();
var showPrice = function(e){
e.stopPropagation();
var vacation = $(this).closest('.vacation');
var button = vacation.find('button');
var price = +vacation.data('price');
var vacation_place = vacation.find('h3').text();
var msg = $("<p style='text-align:center;line-height:24px;font-size:13px;'>Price for " + vacation_place + " is: " + (3 * price) + " </p>");
vacation.find('.msg').prepend(msg).show();
vacation.on('click.remove','button',removePrice);
};
var removePrice = function(e){
e.stopPropagation();
var vacation = $(this).closest('.vacation');
vacation.find('div.msg').hide().find('p').remove();
vacation.on('click.price','button',showPrice);
};
$('.vacation').on('click.price','button',showPrice);
$('.vacation').on('showAll.price',showPrice); // creating a custom event
$('.show-all-price').on('click',function(e){
e.preventDefault();
$('.vacation').trigger('showAll.price'); // firing a custom event on click of an anchor
});
})();
Note:,e.toElement.localName == 'button' doesn't work in IE.
I am trying to style the input[text] and ul list to function as select-option. However, my below code breaks after I selected an option. As the code below, if I select an option from a list, the value of the input[text] change but the list doesn't hide itself. If I uncomment the line in the javascript, the list will hide after I select an option, the list won't show again if I click on the input again. Could anyone help me to fix this problem? I don't know much about jquery and javascript, so I spend couple hours trying to debug but it doesn't fix at all.
$(document).ready(function() {
selecta("#a", "#b")
$("#a").click(function() {
$("#b").show();
});
});
function selecta(a, b) {
$(b + " li").click(function() {
$(b).hide();
/*$(b + " ul").hide();*/
var v = $(this).text();
$(a + " input").val(v);
});
}
.cselect {
position: relative;
}
.cselect input[type]:disabled {
background: #fff;
}
.cselect-menu {
display: none;
position: absolute;
/* top: 0px;*/
left: 0px;
width: 100%;
background: #fff;
}
.cselect-menu ul {
border: 1px solid #d6d6d6;
width: 100%;
}
.cselect-menu li {
padding: 10px 5%;
width: 90%;
}
.cselect-menu li:hover {
background: rgba(41, 128, 185, 0.2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a" class="cselect">
<input type="text" disabled placeholder="Select"/>
<div id="b" class="cselect-menu">
<ul >
<li>Business</li>
<li>Hair</li>
</ul>
</div>
</div>
jsBin demo
Use event.stopPropagation(); to prevent clicks on #b propagate to the parent #a
function selecta(a, b) {
$(b + " li").click(function( event ) {
event.stopPropagation(); // HERE!
$(b).hide();
/*$(b + " ul").hide();*/
var v = $(this).text();
$(a + " input").val(v);
});
}
Frankly... I'f I wanted to use your code on multiple custom-dropdowns of yours I'd go mad with that jQuery...
Here I've simplified HTML, CSS and jQuery:
$(function() { // DOM ready
$(".cselect").each(function(){
var $input = $(this).find("input");
var $dropDown = $(this).find("ul");
$(this).on("click", function(){
$dropDown.stop().slideToggle();
});
$dropDown.on("click", "li", function(){
$input.val( $(this).text() );
});
});
});
*{margin:0; padding:0;} /* ugly reset */
.cselect {
position: relative;
}
.cselect input{
background: #fff;
}
.cselect ul{
display: none;
position: absolute;
z-index:999;
left: 0;
top: 1.2rem;
margin:0;
width: 100%;
background: #fff;
border: 1px solid #d6d6d6;
}
.cselect li {
padding: 10px 5%;
list-style:none;
}
.cselect li:hover {
background: rgba(41, 128, 185, 0.2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cselect">
<input type="text" disabled placeholder="Select n1">
<ul>
<li>Business</li>
<li>Hair</li>
</ul>
</div>
<div class="cselect">
<input type="text" disabled placeholder="Select n2">
<ul>
<li>Something</li>
<li>Else</li>
</ul>
</div>