Is there a better way to append HTML using jQuery - javascript

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>';

Related

A Notepad that keep the notes written even after refresh

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.

Array[0] undefined

When I output my code I get this output:
0[object Object]
1[object Object]
I believe this is because it is an object. Although I'm pretty noob, so I believe an object is an array. Correct me if that's wrong.
I noticed the object in my console:
Objectresult: Objectadmin_county: "Somerset"admin_district: "Sedgemoor"admin_ward: "Axevale"ccg: "NHS Somerset"codes: Objectcountry: "England"eastings: 343143european_electoral_region: "South West"incode: "2WL"latitude: 51.2870673059808longitude: -2.81668795540695lsoa: "Sedgemoor 001A"msoa: "Sedgemoor 001"nhs_ha: "South West"northings: 154531nuts: "Somerset"outcode: "BS26"parish: "Axbridge"parliamentary_constituency: "Wells"postcode: "BS26 2WL"primary_care_trust: "Somerset"quality: 1region: "South West"__proto__: Objectstatus: 200__proto__: Object
it maybe neater to look at this: https://api.postcodes.io/postcodes?lon=0.080647&lat=51.626281000000006&radius=115
I am trying to separate these parts into usable items stored as variables. I tried array[0] but that is undefined. Which I assume means I need to do something more like object(array[0])
I've been searching a while and I'm not getting anywhere.
Here's my full code that I was forking from elsewhere.
$(window).ready(function() {
$(initiate_geolocation);
});
function initiate_geolocation() {
navigator.geolocation.getCurrentPosition(handle_geolocation_query);
}
function handle_geolocation_query(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var url = "https://api.postcodes.io/postcodes?lon=" + lon + "&lat=" + lat + "&radius=125";
post(url).done(function(postcode) {
displayData(postcode);
// console.log("postcode says: "+postcode);
console.log(postcode[0[1]]);
});
}
//display results on page
function displayData(postcode) {
var html = "";
$('#text').hide();
for (var index in postcode['result']) {
html += "<div class='row'>";
html += "<div class='cell'>";
html += index.replace(/_/g, ' ').strFirstUpper();
html += "</div><div class='cell'>";
html += postcode['result'][index];
html += "</div></div>";
console.log(postcode)
}
$('#text').html(html).fadeIn(300);
}
//ajax call
function post(url) {
return $.ajax({
url: url,
success: function() {
//woop
},
error: function(desc, err) {
$('#text').html("Details: " + desc.responseText);
}
});
}
//uppercase
String.prototype.strFirstUpper = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
#import url(//fonts.googleapis.com/css?family=Roboto);
html {
font-family: 'Roboto', sans-serif;
}
.header {
position: fixed;
z-index: 10;
width: 100%;
background: -moz-linear-gradient(90deg, #394D66, #3A5B85);
background: linear-gradient(90deg, #394D66, #3A5B85);
height: 80px;
min-width: 500px;
}
h1 {
font-weight: 400;
text-align: center;
margin: 0px;
font-size: 1.5em;
color: #9DC3EB;
text-transform: uppercase;
}
h1 span {
font-size: 0.8em;
text-transform: lowercase;
color: #E0E0E0;
}
.row {
width: 100%;
font-size: 1.2em;
padding: 5px 0px;
border-bottom: 1px solid #ccc;
}
.inputHolder {
width: 100%;
font-size: 20px;
text-align: center;
}
.inputHolder input {
text-align: center;
color: #333;
}
.cell {
display: inline-block;
width: 49%;
color: #393939;
}
.row .cell:first-child {
text-align: right;
padding-right: 10px;
}
.row:hover {
background: #ccc;
}
#text {
z-index: 0;
padding: 90px 0px;
width: 60%;
margin: 0px auto;
min-width: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
<div class='header'>
<h1><span>Postcode Seach with</span> Postcodes.io</h1>
<!-- <div class='inputHolder'>
<input placeholder='Postcode' type='text' id='txtPostcode'/>
<input type='button' value='Search' id='btnPostcode'/>
</div>
-->
</div>
<div id='text'></div>
Eventually i want this code to ask you for permission to discover your location when you open the page and then find your post code (using postcode.io). I've got most of the way there but my noobishness is hurting me badly. Any help is much appreciated.
The code must be https to run geolocation.

Trying to hide notice for 30 days with the following

I'm trying to hide a notification bar I built after a user clicks x on the following codepen for 30 days based on cookies. I can't seem to figure out how to do this. https://codepen.io/Danskii/pen/aWpoRP
HTML:
<div id="top-site-message-wrapper">
<div id="top-site-message">
Members: you can reduce paper consumption by choosing to receive your membership package by email:
<a href="http://www.oct.ca/" id="top-site-message-CTA">
Yes Please</a>
<button id="top-site-message-hide">
x
</button>
</div>
</div>
CSS:
#top-site-message-wrapper {
background-color: #068edb;
padding: 30px 13px 30px 30px;
border-radius: 3px;
max-width: 100%;
font-size: 16px;
font-style: normal;
font-weight: 600
}
#top-site-message {
color: white;
text-align: center;
}
#top-site-message-CTA {
width: 10%;
color: white;
text-decoration: none;
background: #043d86;
padding: 10px;
border-radius: 3px;
}
#top-site-message-hide {
float: right;
border: none;
color: white;
background-color: blue;
border-radius: 3px;
}
div.yay {
display: none;
}
button.yay {display: none;
}
JS:
// Selects the FIRST occurance of <button>;
var button = document.querySelector("button");
var element = document.querySelector("div");
button.addEventListener("click", function() {
element.classList.toggle("yay");
button.classList.toggle("yay");
});
// Begin script portion for cookies
function TopMessage(){
days=30;
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'TopMessage=Hidden; expires=' + myDate.toGMTString();
}
var cookie = document.cookie.split(';')
.map(function(x){ return x.trim().split('='); })
.filter(function(x){ return x[0]==='TopMessage'; })
.pop();
if(cookie && cookie[1]==='Accepted') {
$("div.yay").hide();
$("button.yay").hide();
}
$('.top-site-message-hide').on('click', function(){
TopMessage();
return false;
});

Hide/show options leaving parent-node showing

I am building a web page dynamically from XML that is the result of an Ajax query. I would like the children divs of each main question div to be hidden when clicked but the main query div to remain shown. The children divs should be shown again when the query div is clicked.
<questionBank title="How Much Do You Know About Sports?">
<question name="Sports Balls">
<picture>xml.jp</picture>
<details>
<query marks="3" bonus="yes">What sport uses an oval ball?</query>
<chapter>1</chapter>
<hint></hint>
</details>
<options>
<opt>Basketball</opt>
<opt>Football</opt>
<opt>Soccer</opt>
<opt>Baseball</opt>
</options>
<answer>
<correct>b</correct>
<description>All other are incorrect</description>
</answer>
<profile>This question shows the the size of a certain sports ball.</profile>
</question>
Here's the html and script (don't mind the counts that is for something else:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="jquery.js"></script>
<script>
var n = 1;
$(document).ready(function() {
mycount = 0;
$.ajax({
type: "GET",
url: "a1q3.xml",
dataType: "xml",
success: parseXML
});
});
function parseXML(xml) {
$("#main").append("<div class='namestyle'>" + $(xml).find("questionBank").attr("title") + "</div>");
$(xml).find("question").each(function() {
$("#main").append("<div class='namestyle1'>" + $(this).attr("name") + "</div><br>");
$("#main").append("<div class='bstyle'>" + $(this).find("query").text() + "</div><br>");
$(this).find("opt").each(function() {
$("#main").append($(this).text() + "<br>");
});
});
};
}
</script>
</head>
<body>
<section id="main"></section>
</body>
</html>
Left out the css didn't think it was needed, just need to have the <'opts'> hidden and then when <'query'>/question is clicked the to show and vice versa (not just one tie as many as the user wants). Here's the css for styling:
<style>
body {
background: black; color: white;
}
.namestyle {
font-size: 1.5em; color: orange;text-align: center; font-weight: bold;
}
.namestyle1 {
font-size: 1.25em; color: orange; text-align: center; font-weight: bold;
}
.bstyle {
font-size: 1em; background: orange; text-align: center; color: black; padding: 5px; border-radius: 10px;
font-weight: bold;
}
.bstyle2 {
font-size: 1.5em; background: orange; color: white; padding: 5px; border-radius: 10px;
}
.list {
border-radius: 20px; background: rgba(100%, 0%, 0%, .5); color: black; padding: 10px;
}
</style>
Thanks.

Best way to toggle between the state of show() and hide() in jQuery

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.

Categories