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>');
Related
How to append text to a specific <div> if i know the ID of the <div>?
For example, here's my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function appendDIV(idDIV, txt) {
$("#" + idDIV).append('<p>' + txt + '</p>');
}
appendDIV("content-01", "some text");
</script>
<div id="content-01" style="float: left; width: 150px; height: 150px; border: 2px solid red;"></div>
Function accepts the ID of the <div> and some text, but nothing happens.
What's going wrong?
code for getting each p in side div you should do like this
Working
// Shorthand for $( document ).ready()
$(function() {
appendDIV("content-01", "some text");
//get all p element and go through each
$('#content-01 > p').each(function( index ) {
console.log( index + ": " + $( this ).text() );
console.log( "id of element" + $(this).attr('id'));
});
});
function appendDIV(idDIV, txt) {
$("#" + idDIV).append('<p>' + txt + '</p>');
}
Working Demo
you should allows to load DOM first before doing any manipulation , so for that you should write you code in document.ready method provided in jquery, which get called when DOM is ready
// Shorthand for $( document ).ready()
$(function() {
appendDIV("content-01", "some text");
});
add code as above. that will do . Read here : $( document ).ready()
You might also consider a custom trigger, passing values, for example if you want a click event on the DIV, then insert some stuff:
$('body').on('appenddiv', function(event, idDIV, txt) {
$("#" + idDIV).append('<p>' + txt + '</p>');
});
// some where later in code:
$(".mydiv-group").on('click', function() {
let myid = $(this).attr('id');
let mytext = myid + ": some text";
$('body').trigger('appenddiv', [myid, mytext]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv-group" id="content-01" style="float: left; width: 150px; height: 150px; border: 2px solid red;"></div>
<div class="mydiv-group" id="content-02" style="float: left; width: 150px; height: 150px; border: 2px solid red;"></div>
This following works when a list item is selected and then hovered and a popover is shown. But when I try to remove popover data attributes from list tag, all the tag removes but the popover does not remove. How to remove the popover such that when an item is not selected, the popover is not shown?
/* Latest compiled and minified JavaScript included as External Resource */
// Checked list box items
$(function() {
$('.list-group.checked-list-box .list-group-item').each(function() {
// Settings
var $widget = $(this),
$checkbox = $('<input type="checkbox" class="hidden" />'),
color = ($widget.data('color') ? $widget.data('color') : "primary"),
style = ($widget.data('style') == "button" ? "btn-" : "list-group-item-"),
settings = {
on: {
icon: 'glyphicon glyphicon-check'
},
off: {
icon: 'glyphicon glyphicon-unchecked'
}
};
$widget.css('cursor', 'pointer')
$widget.append($checkbox);
// Event Handlers
$widget.on('click', function() {
$checkbox.prop('checked', !$checkbox.is(':checked'));
$checkbox.triggerHandler('change');
updateDisplay();
});
$checkbox.on('change', function() {
var id = $(this).closest('li').attr('id');
var isChecked = $checkbox.is(':checked');
if (isChecked) addPopOver(id);
else removePopOver(id);
updateDisplay();
});
function addPopOver(id) {
id = "#" + id;
$(id).attr('data-toggle', "popover");
$(id).attr('data-trigger', "hover");
$(id).attr('data-original-title', $(id).text());
$(id).attr('data-content', "(No items selected)");
$('[data-toggle=popover]').popover();
}
function removePopOver(id) {
id = "#" + id;
$(id).removeAttr("data-toggle");
$(id).removeAttr("data-trigger");
$(id).removeAttr("data-original-title");
$(id).removeAttr("data-content");
}
// Actions
function updateDisplay() {
var isChecked = $checkbox.is(':checked');
// Set the button's state
$widget.data('state', (isChecked) ? "on" : "off");
// Set the button's icon
$widget.find('.state-icon')
.removeClass()
.addClass('state-icon ' + settings[$widget.data('state')].icon);
// Update the button's color
if (isChecked) {
$widget.addClass(style + color + ' active');
} else {
$widget.removeClass(style + color + ' active');
}
}
// Initialization
function init() {
if ($widget.data('checked') == true) {
$checkbox.prop('checked', !$checkbox.is(':checked'));
}
updateDisplay();
// Inject the icon if applicable
if ($widget.find('.state-icon').length == 0) {
$widget.prepend('<span class="state-icon ' + settings[$widget.data('state')].icon + '"></span>');
}
}
init();
});
$('#get-checked-data').on('click', function(event) {
event.preventDefault();
var checkedItems = {},
counter = 0;
$("#check-list-box li.active").each(function(idx, li) {
checkedItems[counter] = $(li).text();
counter++;
});
$('#display-json').html(JSON.stringify(checkedItems, null, '\t'));
});
});
/* Check Box For item required */
.state-icon {
left: -5px;
}
.list-group-item-primary {
color: rgb(255, 255, 255);
background-color: rgb(66, 139, 202);
}
/* DEMO ONLY - REMOVES UNWANTED MARGIN */
.well .list-group {
margin-bottom: 0px;
}
.list-inline>li {
display: inline-block;
padding-right: 12px;
padding-left: 20px;
margin-bottom: 3px;
font-size: 17px;
}
#check-list-box {
padding: 10px;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<ul id="check-list-box" class="list-group checked-list-box list-inline ">
<li class="list-group-item event-item" id="venue" data-color="danger">Venue</li>
<li class="list-group-item event-item" id="catering" data-color="info">Catering</li>
<li class="list-group-item event-item" id="desserts" data-color="warning">Desserts</li>
<li class="list-group-item event-item" id="photographer" data-color="success">Photographer</li>
<li class="list-group-item event-item" id="bus" data-color="danger">Party buses</li>
<li class="list-group-item event-item" id="castles" data-color="danger">Bouncy Castles</li>
<li class="list-group-item" data-color="danger">Other</li>
<!--<input type="textbox" name ="other" >-->
</ul>
You could use .popover('destroy').
function removePopOver(id) {
id = "#" + id;
$(id).popover('destroy')
}
To destroy the shown popover you can use the following code-snippet:
function removePopOver(id) {
id = "#" + id;
$(id).popover('dispose'); // JQuery > 4.1
// $(id).popover('destroy'); // JQuery < 4.1
}
You can also remove all created popovers from your DOM via .popover class (of course each popover has its own id, so by knowing the IDs you can be more precise)
$('.popover').remove();
I'm trying to make a to-do list with an edit button, that when clicked, will make added items editable, but am having trouble. I have the button created and everything, but when I click it nothing happens. Any advice would be greatly appreciated!
JavaScript
function editItem(){
var parent = $(this).parent();
if (!parent.hasClass('edit')) {
parent.addClass('edit');
}else if (parent.hasClass('edit')) {
var editTask = $(this).prev('input[type="text"]').val();
var editLabel = parent.find('label');
editLabel.html(editTask);
parent.removeClass('edit');
}
$(function(){
$(document).on('click', 'edit', editItem)
});
Looks like you are targeting <edit>, you are supposed to use .edit:
$(function(){
$(document).on('click', '.edit', editItem);
});
Working Snippet
$(function () {
function addItem () {
// append to the list
$("#todo-items").append('<li><span>' + $("#todo").val() + '</span> <small>Edit • Delete</small></li>');
// clear the text
$("#todo").val("");
}
$("#todo").keydown(function (e) {
// if enter key pressed
if (e.which == 13)
addItem();
});
// on clicking the add button
$("#add").click(addItem);
// delegate the events to dynamically generated elements
// for the edit button
$(document).on("click", 'a[href="#edit"]', function () {
// make the span editable and focus it
$(this).closest("li").find("span").prop("contenteditable", true).focus();
return false;
});
// for the delete button
$(document).on("click", 'a[href="#delete"]', function () {
// remove the list item
$(this).closest("li").fadeOut(function () {
$(this).remove();
});
return false;
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none; text-decoration: none;}
input, li {padding: 3px;}
#todo-items small {display: inline-block; margin-left: 10px; padding: 2px; vertical-align: bottom;}
#todo-items span:focus {background-color: #ccf;}
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<input type="text" id="todo" />
<input type="button" value="Add" id="add" />
<ul id="todo-items"></ul>
my use case : create tab like experience. clicking on add button creates a (horz tab button) and a corresponding div, which is linked via onclick listener, dynamically.
problems :
on clicking add button, values from previous tabs are reset (which is obvious wrt to the way $tabs_prev & $menu_prev is populated) and
their respective js goes away (which I can't understand, why?)
a remove tab implementation (because the way I've coded these tabs, removing a tab and corresponding div isn't really simple, so, any clues in this direction, maybe?)
code : fiddle : http://jsfiddle.net/g58fzs75/1/
HTML:
<body>
<input id="hidden" type="hidden" value="1"></input>
<div id="template_tabBtn" style="display:none">
<input type="button" value="add" onclick="addTab()"></input>
</div>
<ul id="menu">
</ul>
<div id="tabs">
</div>
<div id="template_tabBar" style="display:none">
<li>
<input type="button" id="tab_btn" class="template_tabBar" value="Tab" onclick="tabClick(this)"></input>
</li>
</div>
<div id="template_tabs" style="display:none">
<div id="tabs" class="template_tabs tab_div" value="1">
<input type="text" id="txt" class="template_tabs" value="alert"></input>
<input type="button" id="btn" class="template_tabs" value="alert"></input>
</div>
</div>
</body>
CSS:
<style>
ul#menu {
padding: 0;
}
ul#menu li {
display: inline;
}
ul#menu li input {
background-color: black;
color: white;
padding: 10px 20px;
text-decoration: none;
border-radius: 4px 4px 0 0;
}
ul#menu li input:hover {
background-color: orange;
}
</style>
jQuery :
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script>
$tabs_prev = "";
$menu_prev = "";
$add_btn = "";
$current_tabID = "";
function tabClick(id) {
showCurrent($(id).attr('id'));
}
function addTab() {
var tabCount = parseInt($('#hidden').val()) + 1;
$('#hidden').val(tabCount);
run(tabCount);
showCurrent($('#tabs-' + tabCount).attr('id'));
}
$(document).ready(function() {
$add_btn = "<li>" + $('#template_tabBtn').html() + "</li>";
run(1);
});
function run(tabCount) {
//$tabs_prev += main($('#template_tabs'),tabCount);//alert("tabs\n"+$tabs_prev);
$menu_prev += main($('#template_tabBar'), tabCount); //alert("menu\n"+$menu_prev);
$('#tabs').html($('#tabs').html() + main($('#template_tabs'), tabCount));
$('#menu').html($menu_prev + $add_btn);
logic(tabCount);
}
function main(target, tabCount) {
$htmlBackup = $(target).html();
$('.' + $(target).attr('id')).each(function() {
$(this).attr('id', $(this).attr('id') + "-" + tabCount).removeClass($(target).attr('id'));
$(this).attr('value', $(this).attr('value') + "-" + tabCount);
});
$html = $(target).html();
$(target).html($htmlBackup);
return $html;
}
function logic(tabCount) {
$('#btn-' + tabCount).click(function() {
alert($('#txt-' + tabCount).val());
});
}
function showCurrent(current_id) {
$('.tab_div').each(function() {
var id = $(this).attr('id');
var id_num = id.substr(id.lastIndexOf('-') + 1, id.length);
var current_id_num = current_id.substr(current_id.lastIndexOf('-') + 1, current_id.length);
if (id_num == current_id_num) {
$("#tabs-" + id_num).show();
$('#tab_btn-' + id_num).css({
"background-color": "orange"
});
} else {
$("#tabs-" + id_num).hide();
$('#tab_btn-' + id_num).css({
"background-color": "black"
});
}
});
}
</script>
The reason why your javascript is disappearing is because resetting the innerHTML deletes the onclick handlers on the elements. Why: the original elements are destroyed, including references to events and new elements are created.
The code responsible for this:
$('#tabs').html($('#tabs').html() + main($('#template_tabs'), tabCount));
Please use jQuery's appending of an element by cloning the template tab:
$('#tabs').append($('#template_tabs').clone(true));
Append appends htmlstrings or elements to an parent element. It's a buffed up version of the documents native 'appendChild'.
clone clone the template element (makes a copy). You can do this in your function main and return it to the append function.
function main(tabCount)
{
var node = $('#template_tabs').clone(true));
//do things with the node, like setting an onclick handler, or id.
//example
node.setAttribute("id", "tab" + tabCount);
}
Removing can be done also:
function removeNode(node)
{
//provide a node via jQuery
//example: removeNode($("#tab2")) <-- now tab2 will be removed from the DOM.
node.remove();
}
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