I'm trying to fix my jQuery code. I want 'add content' button in the last div only. If a div is removed, the button stays in the last div. Suggestions please.
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) $(".question").html('');
$(".hide_button").remove();
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question' + i + '">Remove</div><b>Question ' + i + '</b><br> This is div text <br> <button class="addcontent hide_button' + i + '">Add content</button></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
$(".question").append('<button class="addcontent hide_button">Add content</button>').show('slow');
}
});
});
HTML:
<div class="question">
<button class="addcontent hide_button">Add content</button>
</div>
Try this:
Move your button out of your div:
HTML:
<div class="question">
</div>
<button class="addcontent hide_button">Add content</button>
JS:
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) $(".question").html('');
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question' + i + '">Remove</div><b>Question ' + i + '</b><br> This is div text <br></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
}
});
});
JSFIDDLE: http://jsfiddle.net/ghorg12110/a7L3cn1a/1/
Here is the updated/working code.
HTML:
<div>
<div class="question"></div>
<button class="addcontent">Add content</button>
</div>
JavaScript:
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) {
$(".question").html('');
}
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question'+i+'">Remove</div><b>Question ' + i + '</b><br> This is div text <br></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
}
});
});
A little hard to see what you have in mind, but I would have the button in all the divs and use CSS to show or hide the button.
div button { display: none; }
div:last-of-type button { display: inline; }
It's more efficient if you use CSS to overlap that property at the end and you will conserve the same element with the necessity of adding and removing it
html:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="content" class="content"></div>
<button class="addcontent hide_button">Add content</button>
</body>
</html>
css:
.new-question {
background-color: green;
width: 300px;
height: auto;
position: relative;
margin:0;
}
.deleteButton {
background-color: red;
width: 50px;
height: 50px;
margin-left: 100%;
position: relative;
}
.addcontent{
z-index: 1;
top:-25px;
left:200px;
position:relative;
}
.content{
min-height:30px;
}
js:
$(function (){
var i = 1,
contentQuestion = $('<div class="new-question"></div>'),
remove = $('<div class="deleteButton">Remove</div>').appendTo(contentQuestion),
content = $('#content');
$('.addcontent').on('click', function () {
content.append(contentQuestion.clone().append('<b>Question ' + i + '</b><br> This is div text'));
i += 1;
});
content.on('click', '.deleteButton', function () {
$(this.parentNode).remove();
});
});
jsbin:
http://jsbin.com/gequveroba/1/edit?html,css,js,output
Related
Instead of adding the item to the list using an add button and then removing the appended item using a remove button, how do I make them the same button (or input) so that if it is checked the item is appended to the list and if it is unchecked it is removed from the list?
I need the add and remove to be the same button so that I can remove the item from the list by either unchecking the item button OR the appended item's button.
// Wish Function
var wish = {
items: []
};
var update_product = function(product) {};
$(function() {
//Add to wish
var addToWish = function(product, qty) {
qty = qty || 1;
var wish = getWish();
var indexOfId = wish.items.findIndex(x => x.id == product.id);
if (indexOfId === -1) {
wish.items.push({
id: product.id,
img: product.img,
name: product.name,
});
$parent = $("#" + product.id).closest(".items__wish");
$parent
.find(".wish-icon")
.addClass("active")
.attr("data-prefix", "fas");
} else {
wish.items[indexOfId].qty++;
wish.items[indexOfId].stock = Number(product.stock);
}
//Update popup wish
updateWish(wish);
};
var getProductValues = function(element) {
var productId = $(element)
.closest(".items__wish")
.find(".item__tile")
.attr("id");
var productImg = $(element)
.closest(".items__wish")
.find(".item__img")
.attr("src");
var productName = $(element)
.closest(".items__wish")
.find(".item__title")
.html();
return {
id: productId,
img: productImg,
name: productName,
};
};
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
addToWish({
id: product.id,
img: product.img,
name: product.name,
});
});
//Update wish html to reflect changes
var updateWish = function(wish) {
//Add to shopping wish dropdown
$(".wishlist__items").html("");
for (var i = 0; i < wish.items.length; i++) {
$(".wishlist__items").append(
"<li>" +
'<div class="my-wish-item">' +
"<img src='" +
wish.items[i].img +
"' />" +
'<div class="wish-main">' +
'<div class="wish-name">' +
wish.items[i].name +
"</div>" +
'<div class="my-wish-remove-container">' +
'<input type="checkbox" id="my-wish-remove' +
i +
'" class="my-wish-remove" aria-hidden="true">' +
"<i class='fas fa-heart'></i>" +
"</div>"
);
//Remove from wish on id
var removeFromWish = function(id) {
var wish = getWish();
var wishIndex = wish.items.findIndex(x => x.id == id);
wish.items.splice(wishIndex, 1);
$parent = $("#" + id).closest(".items__wish");
$parent
.find(".wish-icon")
.first()
.removeClass("active")
.attr("data-prefix", "far");
//Update popup wish
updateWish(wish);
};
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
removeFromWish(wish.items[currentIndex].id);
}, 400);
});
})();
}
};
//Get Wish
var getWish = function() {
var myWish = wish;
return myWish;
};
});
body {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
}
img {
width: 50px;
}
.wishlist__list {
position: absolute;
right: 0;
}
.wishlist__items li {
list-style: none;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="items__wish">
<div id='1' class='item__title item__tile'>Product 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></input></label>
</div>
<div class="items__wish">
<div id='2' class='item__title item__tile'>Product 2</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></input></label>
if your aim is only to manage wished list by checkboxes this code should be sufficient.
var addedProducts = [];
$(document).on('click', '.items__wish', function() {
var item = $(this);
var itemIndex = item.index();
if (item.parents('.wishlist__items').length > 0) {
itemIndex = parseInt(item.attr('data-index'))
}
if (item.find('.my-wish-add').prop('checked') && addedProducts.indexOf(itemIndex) < 0) {
if (item.parents('.wishlist__items').length == 0) {
item.clone().attr('data-index', itemIndex).appendTo($('.wishlist__items'))
addedProducts.push(itemIndex)
}
}
else if (item.find('.my-wish-add').prop('checked')==false && addedProducts.indexOf(itemIndex) >= 0) {
$('.products .items__wish').eq(itemIndex).find('.my-wish-add').prop('checked', false);
$('.wishlist__items .items__wish[data-index="' + itemIndex + '"]').remove();
addedProducts.splice( addedProducts.indexOf(itemIndex), 1 );
}
});
body {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
}
img {
width: 50px;
}
.wishlist__list {
position: absolute;
right: 0;
}
.wishlist__items li {
list-style: none;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="items__wish">
<div id='1' class='item__title item__tile'>Product 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></input></label>
</div>
<div class="items__wish">
<div id='2' class='item__title item__tile'>Product 2</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></input></label>
Update: You may consider moving removeFromWish() to the same scope as addToWish() so that it is accessible to other functions.
You can use jquery to see if the checkbox is checked, then either append the item or remove the item from the list accordingly.
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
if ($(this).is(":checked")) {
addToWish({
id: product.id,
img: product.img,
name: product.name,
});
} else {
removeFromWish(product.id);
}
});
Making these two changes should be able to solve your problem. If you want to uncheck the checkbox upon removal of the list item, you can also try the following:
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
removeFromWish(wish.items[currentIndex].id);
// uncheck (productID - 1)th checkbox
$(".my-wish-add").eq(wish.items[currentIndex].id - 1).prop("checked", false);
}, 400);
});
})();
Unchecking a checkbox like this may not be very clear. I hope you get the basic idea and adapt this code so that it fits your style.
[Updated] Demo:
// Wish Function
var wish = {
items: []
};
var update_product = function(product) {};
$(function() {
//Add to wish
var addToWish = function(product, qty) {
qty = qty || 1;
var wish = getWish();
var indexOfId = wish.items.findIndex(x => x.id == product.id);
if (indexOfId === -1) {
wish.items.push({
id: product.id,
img: product.img,
name: product.name,
});
$parent = $("#" + product.id).closest(".items__wish");
$parent
.find(".wish-icon")
.addClass("active")
.attr("data-prefix", "fas");
} else {
wish.items[indexOfId].qty++;
wish.items[indexOfId].stock = Number(product.stock);
}
//Update popup wish
updateWish(wish);
};
//Remove from wish on id
var removeFromWish = function(id) {
var wish = getWish();
var wishIndex = wish.items.findIndex(x => x.id == id);
wish.items.splice(wishIndex, 1);
$parent = $("#" + id).closest(".items__wish");
$parent
.find(".wish-icon")
.first()
.removeClass("active")
.attr("data-prefix", "far");
//Update popup wish
updateWish(wish);
};
var getProductValues = function(element) {
var productId = $(element)
.closest(".items__wish")
.find(".item__tile")
.attr("id");
var productImg = $(element)
.closest(".items__wish")
.find(".item__img")
.attr("src");
var productName = $(element)
.closest(".items__wish")
.find(".item__title")
.html();
return {
id: productId,
img: productImg,
name: productName,
};
};
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
if ($(this).is(":checked")) {
addToWish({
id: product.id,
img: product.img,
name: product.name,
});
} else {
removeFromWish(product.id);
}
});
//Update wish html to reflect changes
var updateWish = function(wish) {
//Add to shopping wish dropdown
$(".wishlist__items").html("");
for (var i = 0; i < wish.items.length; i++) {
$(".wishlist__items").append(
"<li>" +
'<div class="my-wish-item">' +
"<img src='" +
wish.items[i].img +
"' />" +
'<div class="wish-main">' +
'<div class="wish-name">' +
wish.items[i].name +
"</div>" +
'<div class="my-wish-remove-container">' +
'<input type="checkbox" id="my-wish-remove' +
i +
'" class="my-wish-remove" aria-hidden="true">' +
"<i class='fas fa-heart'></i>" +
"</div>"
);
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
$(".my-wish-add").eq(wish.items[currentIndex].id - 1).prop("checked", false);
removeFromWish(wish.items[currentIndex].id);
}, 400);
});
})();
}
};
//Get Wish
var getWish = function() {
var myWish = wish;
return myWish;
};
});
body {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
}
img {
width: 50px;
}
.wishlist__list {
position: absolute;
right: 0;
}
.wishlist__items li {
list-style: none;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="items__wish">
<div id='1' class='item__title item__tile'>Product 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></input></label>
</div>
<div class="items__wish">
<div id='2' class='item__title item__tile'>Product 2</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></input></label>
Here's a much cleaner implementation of the required functionality using buttons. You can just as easily change it to use checkboxes instead.
Pro-tip: While I understand you might have specific requirements, I'd recommend using a component based design approach and considering using pure JavaScript instead of third party libraries like jQuery.
$(function() {
$("li button").click(function(event) {
let targetList = '';
if ($(event.target).closest(".list").attr('id') === 'product-list') {
targetList = '#wish-list ul';
targetLabel = 'Remove';
} else {
targetList = '#product-list ul';
targetLabel = 'Add';
}
event.target.innerHTML = targetLabel;
$(event.target).closest("li").appendTo(targetList);
})
$("#btn-display-list").click(function() {
alert(JSON.stringify(getListInfo('#wish-list')));
})
});
function getListInfo(type) {
const list = [];
$(type + " li").each(function(i, target) {
list.push({
id: $(target).attr("id"),
img: $(target).find("img").attr("src"),
name: $(target).find("h4").html()
})
})
return list;
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
color: #ddd;
font-weight: lighter;
}
.container {
display: flex;
}
.list {
width: 50%;
}
ul {
padding: 0px;
}
li {
list-style-type: none;
}
li img,
li div {
display: inline-block;
margin-bottom: 10px;
vertical-align: top;
}
li img {
max-width: 70px;
}
li h4 {
margin: 0px;
}
h4,
h3 {
font-weight: lighter;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="product-list" class="list">
<h3>Product Catalog</h3>
<ul>
<li id='prod-001'>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<div>
<h4>product 1</h4>
<button>Add</button>
</div>
</li>
<li id='prod-002'>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<div>
<h4>product 2</h4>
<button>Add</button>
</div>
</li>
</ul>
</div>
<div id="wish-list" class="list">
<h3>Wishlist</h3>
<ul>
</ul>
</div>
</div>
<hr/>
<button id="btn-display-list">Show Wishlist</button>
When a button is clicked, its background-color does not become yellow as intended nor does the previously clicked button's background-color revert to red. My goal is to change the buttons' colors when they are clicked by changing their classes. When the buttons' classes are changed they do not change color. The purpose of testFunction() is updating the color of the buttons. The purpose of testFunction2() is adding an onclick function to the buttons.
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<style>
.button {
background-color: red;
}
.c {
background-color: yellow;
}
</style>
<body>
<table>
<tr>
<td>test1</td>
</tr>
<tr>
<td id="test1">
<button class="c">0</button>
<button class="">1</button>
<button class="">2</button>
<button class="">3</button>
</td>
</tr>
<tr>
<td>test2</td>
</tr>
<tr>
<td id="test2">
<button class="c">0</button>
<button>1</button>
<button>2</button>
<button>3</button>
</td>
</tr>
</table>
<script>
var lastClick1 = 0;
var lastClick2 = 0;
//alert('js');
function testFunction(c, n) {
// alert('tf');
if (c == 0) {
// alert('s=0');
if (lastClick1 != n) {
var a = document.getElementById("test1").children;
a[lastClick1].class = '';
a[n].class = 'c';
alert('n: ' + n + ' class: ' + a[n].class);
alert('lastclick:' + lastClick1 + ' class: ' + a[lastClick1].class);
lastClick1 = n;
}
} else {
// alert('else');
if (lastClick2 != n) {
var b = document.getElementById("test2").children;
b[lastClick2].class = '';
b[n].class = 'c';
alert('n: ' + n + ' class: ' + b[n].class);
alert('lastclick:' + lastClick2 + ' class: ' + b[lastClick2].class);
lastClick2 = n;
}
}
}
function testFunction2() {
//alert('tf2');
var t1 = document.getElementById("test1").children;
var t2 = document.getElementById("test2").children;
//alert(t1);
for (var i = 0; i < 6; i++) {
t1[i].onclick = function() {
testFunction(0, parseInt(this.innerText));
};
t2[i].onclick = function() {
testFunction(1, parseInt(this.innerText));
};
}
}
testFunction2();
</script>
</body>
</html>
Add to jQuery
link
CSS
.button {
background-color: red;
}
.c {
background-color: yellow;
}
.r{
background-color: red;
}
Jquery
$(function(){
$('button').on('click', function () {
$(this).parent('td').children('.c').removeClass('c').addClass('r');
$(this).addClass('c');
})
});
I am trying to make a tooltip with JQuery for incoming list items. People will enter some text in a textfield, hit enter and those values will be added to a visible list on the site. I want to make a tooltip for every list item that will be added to the list. I want the text that people fill in in the textfield to be added in the tooltip, is this possible? And how can I do this? Thanks! This is what I have so far..
<div id="tooltip"></div>
<input type="text" id="input" placeholder="Voer item in" /> <button id="button">Toevoegen</button>
<ul id="boodschappenlijst">
</ul>
----------------------------------------------------------------------------
$(document).ready(function(e) {
$('#button').on('click', function (){
var toevoegen = $('#input').val();
var verwijderen = 'Verwijderen'
<!--add list item-->
$('#boodschappenlijst').prepend('<li>' + toevoegen + '' + '\t' + verwijderen + '</li>');
});
<!--remove list item-->
$('#boodschappenlijst').on('click', '.verwijderen', function(){
$(this).parent('li').remove();
});
<!-textfield empty-->
$('#input').on('click', function (){
$(this).val('')
});
$('#boodschappenlijst').hover(
function (){
$('#tooltip').css('display', 'block')
},
function (){
$('#tooltip').css('display', 'none')
};
);
}) ;
----------------------------------------------------------------
#tooltip {
position: absolute;
top: 100px;
right: 300px;
border: 1px solid #000000;
border-radius: 5px;
color: black;
width: 100px;
display: none;
}
The tooltip appears, but I want the text that people fill in in the textfield to be added in the tooltip. If you need some more information just ask. Thanks in advance (verwijderen = remove, toevoegen = add)
There are two main changes you need to make:
You need to store toevoegen with the li in a structured way.
You need to attach the hover event to the li, not the ul - or more specifically any lis which are added to the ul in future.
For 1. you can use the jquery data() to store the tooltip value:
var li = $('<li>' + toevoegen + '' + '\t' + verwijderen + '</li>');
li.data('tooltip', toevoegen);
$('#boodschappenlijst').prepend(li);
For 2. you will need to use on() instead of hover() to ensure that new lis get the event attached:
$('#boodschappenlijst').on('mouseenter', 'li', function () {
var toevoegen = $(this).data('tooltip');
$('#tooltip').css('display', 'block').html(toevoegen);
}).on('mouseleave', 'li', function () {
$('#tooltip').css('display', 'none').html('');
});
Here is the full thing, tidied up:
$(document).ready(function (e) {
$('#button').on('click', function () {
var toevoegen = $('#input').val();
var verwijderen = 'Verwijderen'
//add list item
var li = $('<li>' + toevoegen + '' + '\t' + verwijderen + '</li>');
li.data('tooltip', toevoegen);
$('#boodschappenlijst').prepend(li);
});
// remove list item
$('#boodschappenlijst').on('click', '.verwijderen', function () {
$(this).parent('li').remove();
});
// textfield empty
$('#input').on('click', function () {
$(this).val('');
});
$('#boodschappenlijst').on('mouseenter', 'li', function () {
var toevoegen = $(this).data('tooltip');
$('#tooltip').css('display', 'block').html(toevoegen);
}).on('mouseleave', 'li', function () {
$('#tooltip').css('display', 'none').html('');
});
});
#tooltip {
position: absolute;
top: 100px;
right: 300px;
border: 1px solid #000000;
border-radius: 5px;
color: black;
width: 100px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="tooltip"></div>
<input type="text" id="input" placeholder="Voer item in" /> <button id="button">Toevoegen</button>
<ul id="boodschappenlijst"></ul>
UPDATED ANSWER.
Working example
$(document).ready(function(e) {
var myToolTip = $('#tooltip');
$('#button').on('click', function (){
var toevoegen = $('#input').val();
var verwijderen = 'Verwijderen'
$('#boodschappenlijst').prepend('<li class=\'hoverTarget\' title=\''+toevoegen+' \'>' + toevoegen + '' + '\t' + verwijderen + '</li>');
$('.hoverTarget').hover(
function (_evt){
console.log("e",_evt);
console.log("e",_evt.currentTarget.attributes['title']);
myToolTip.html(_evt.currentTarget.attributes['title'].value);
myToolTip.css('display', 'block')
},
function (){
myToolTip.css('display', 'none')
}
);
});
$('#boodschappenlijst').on('click', '.verwijderen', function(){
$(this).parent('li').remove();
});
$('#input').on('click', function (){
$(this).val('')
});
}) ;
Add title attribute to your line item
$('#boodschappenlijst').prepend('<li title=\''+toevoegen+'\'>' + toevoegen + '' + '\t' + verwijderen + '</li>');
i need to initialize the owl carousel inside a click event like the following code, it works in first time when I click, but when I click it again (on event div) it simply doesn't work. how can I accomplish that? is there a way to reset the owl carousel?
I added my full code to the last part of this post to understand better my pb and to test it.
Could you please help me on this? I really need this.
thanks in advance,
CAFC
source owl carousel : http://owlgraphic.com/owlcarousel/demos/customJson.html
$('#XX').click(function(e) {
e.PreventDefault;
$("#owl-demo").owlCarousel({
jsonPath: 'json/customData2.json',
jsonSuccess: customDataSuccess
});
function customDataSuccess(data) {
var content = "";
for (var i in data["items"]) {
var img = data["items"][i].img;
var alt = data["items"][i].alt;
content += "<img src=\"" + img + "\" alt=\"" + alt + "\">"
}
$("#owl-demo").html(content);
}
});
my full code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Owl Carousel - Dynamic content via JSON</title>
<!-- Owl Carousel Assets -->
<link href="../owl-carousel/owl.carousel.css" rel="stylesheet">
<link href="../owl-carousel/owl.theme.css" rel="stylesheet">
<script src="../assets/js/jquery-1.9.1.min.js"></script>
<script src="../owl-carousel/owl.carousel.js"></script>
<!-- Demo -->
<style>
#owl-demo .item {
background: #a1def8;
padding: 10px 0px;
display: block;
margin: 5px;
color: #FFF;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
text-align: center;
}
</style>
<script>
$(document).ready(function() {
$('#XX').click(function(e) {
$("#owl-demo").owlCarousel({
jsonPath: 'json/customData2.json',
jsonSuccess: customDataSuccess
});
function customDataSuccess(data) {
var content = "";
for (var i in data["items"]) {
var img = data["items"][i].img;
var alt = data["items"][i].alt;
content += "<img src=\"" + img + "\" alt=\"" + alt + "\">"
}
$("#owl-demo").html(content);
}
});
});
</script>
</head>
<body>
<div id="owl-demo"></div>
<div id='XX'>Click HERE!</div>
</body>
</html>
Here ya go:
JS:
$(document).ready(function () {
var owl = false;
$('#XX').click(function (e) {
if (owl) {
$("#owl-demo").data('owlCarousel').reinit({
jsonPath: '/echo/json',
jsonSuccess: customDataSuccess
});
} else {
owl = true;
}
$("#owl-demo").owlCarousel({
jsonPath: '/echo/json',
jsonSuccess: customDataSuccess
});
function customDataSuccess(data) {
console.log('loading Data');
data = testJSON;
var content = "";
for (var i in data["items"]) {
var img = data["items"][i].img;
var alt = data["items"][i].alt;
content += "<img src=\"" + img + "\" alt=\"" + alt + "\">";
}
$("#owl-demo").html(content);
}
});
});
The methods of reinit are found at the bottom of the documentation under 5. Owl Data methods
Demo: http://jsfiddle.net/robschmuecker/pLvdx8xx/
I am working on a tutorial that uses getJSON to add list items to the DOM. There also needs to be the JqueryUI sortable plugin to sort the lists. For some reason unknown to me the plugin does not work. What am I missing here? Should the sortable function be inside the getJSON callback? Any suggestions would be great.
here is my code I have so far:
$(function () {
$('body h1').append('My Todo List');
$.getJSON('todo.json', function(data) {
var html = '<ul id="sortable" class="ui-sortable">';
$.each(data, function(index) {
var todo = data[index];
if (todo.done === false) {
todo.done = (" ")
} else {
todo.done = ("(DONE)")
}
html += '<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' + todo.who + " needs to " + todo.task + " by " + todo.dueDate + " " + todo.done + '</li>';
});
html += '</ul>';
$('body #container').append(html);
});
});
HTML File:
<!DOCTYPE html>
<html>
<head>
<title>Jquery ToDo List</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="todo.js"></script>
<script>
$(function () {
$("#sortable").sortable("refresh");
$("#sortable").disableSelection("refresh");
});
</script>
<style>
#sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 14px; height: 18px; }
#sortable li span { position: absolute; margin-left: -1.3em; }
</style>
</head>
<body>
<h1></h1>
<div id="container">
</div>
</body>
</html>
JSON
[
{"task":"get milk","who":"Scott","dueDate":"2013-05-19","done":false},
{"task":"get broccoli","who":"Elisabeth","dueDate":"2013-05-21","done":false},
{"task":"get garlic","who":"Trish","dueDate":"2013-05-30","done":false},
{"task":"get eggs","who":"Josh","dueDate":"2013-05-15","done":true}
]
you have to call the sortable after appending the data. In your $.getJSON callback call the sortable again like given below. jquery will wire the sortable only if the element is present in the DOM when the dom is ready. you are adding the elements dynamically so you have to call the sortable again after adding the elements into the DOM.
$.getJSON('todo.json', function(data) {
var html = '<ul id="sortable" class="ui-sortable">';
$.each(data, function(index) {
var todo = data[index];
if (todo.done === false) {
todo.done = (" ")
} else {
todo.done = ("(DONE)")
}
html += '<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' + todo.who + " needs to " + todo.task + " by " + todo.dueDate + " " + todo.done + '</li>';
});
html += '</ul>';
$('body #container').append(html);
});
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
});
Edit
Here is the bin http://jsbin.com/IPubElE/1/
demo uses the in-memory data but it should work fine even inside the callback method.