Removing a bootstrap popover dynamically using jquery - javascript

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();

Related

How to save results to localStorage

I am new in HTML and jQuery, and this was my first implementation, and I am not sure it's correct, I need your help, I tried to make simple counter to begin counting per click, and to store the results in localStorage, this is all I could do
but it didn't work, may you tell me what I've done wrong?
Thanks
$(function() {
$('.container li').click(function() {
var btn = $(this).attr("data-page");
var element = $('.counter[data-page="' + btn + '"]').html();
element++
$('.counter[data-page="' + btn + '"]').html(element);
localStorage.setItem('save', $('.counter[data-page="' + btn + '"]').html());
if (localStorage.getItem('save')) {
$('.counter[data-page="' + btn + '"]').html(localStorage.getItem('save'));
}
});
});
ul {
padding: 0;
margin: 0;
list-style: none;
}
a {
text-decoration: none;
background: blue;
color: #fff;
padding: 10px;
}
ul li {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li data-page="facebook">
4100
</li>
<li data-page="twitter">
4100
</li>
</ul>
You need to init first your buttons with values from localStorage. Then you don't need to retrieve them again, you just need to manipulate the value inside the html and to set the new counter in the localStorage.
Also you need to have one counter by button in your localStorage
// Just to make this snippet work,
// because localStorage is forbiden here
// database = localStorage
database = {
store: {},
getItem: function(key) {
return this.store[key];
},
setItem: function(key, val) {
this.store[key] = val;
},
}
$(function() {
$(".counter").each((_, element) => {
const $btn = $(element);
const key = `save-${$btn.attr("data-page")}`;
$btn.html(database.getItem(key) || 0);
});
$(".container li").click(function() {
const $btn = $(this).find(".counter");
const key = `save-${$btn.attr("data-page")}`;
const counter = (+$btn.html()) + 1;
$btn.html(counter);
database.setItem(key, counter);
});
});
ul {
padding: 0;
margin: 0;
list-style: none;
}
a {
text-decoration: none;
background: blue;
color: #fff;
padding: 10px;
}
ul li {
display: inline-block;
}
<ul class="container">
<li data-page="facebook">
4100
</li>
<li data-page="twitter">
4100
</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to load the data from the local storage when the page loads. Right now it only loads after saving, which has no effect.
Each element is also saving to the same part of the local storage, so they will be the same every time the page loads. You need to save to an index based on the data-page.
Here you go with one more solution https://jsfiddle.net/thrh78u0/
$(function() {
$('.container li').click(function() {
var btn = $(this).attr("data-page");
var element = $('.counter[data-page="' + btn + '"]').html();
element++
$('.counter[data-page="' + btn + '"]').html(element);
localStorage.setItem('save' + btn, element);
if (localStorage.getItem('save')) {
$('.counter[data-page="' + btn + '"]').html(localStorage.getItem('save'));
}
});
});
ul {
padding: 0;
margin: 0;
list-style: none;
}
a {
text-decoration: none;
background: blue;
color: #fff;
padding: 10px;
}
ul li {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li data-page="facebook">
4100
</li>
<li data-page="twitter">
4100
</li>
</ul>
Hope this will help you.
Try this simple one:
$('.container li').click(function() {
if (localStorage.count) {
localStorage.count++
} else {
localStorage.count = 1;
}
})
Updated script using different variables for different counters. It loads counters values from localStorage or sets them to 0 if not available. It also uses two separate variables to store the values.
I used your code so you can see what is different and what you missed in your solution
$(function() {
var cntfb = localStorage.getItem('save-facebook');
$('.counter[data-page="facebook"]').html(cntfb ? cntfb : 0);
var cnttw = localStorage.getItem('save-twitter');
$('.counter[data-page="twitter"]').html(cnttw ? cnttw : 0);
$('.container li').click(function() {
var btn = $(this).attr("data-page");
var element = $('.counter[data-page="' + btn + '"]').html();
element++;
$('.counter[data-page="' + btn + '"]').html(element);
localStorage.setItem('save-' + btn, $('.counter[data-page="' + btn + '"]').html());
if (localStorage.getItem('save-' + btn)) {
$('.counter[data-page="' + btn + '"]').html(localStorage.getItem('save-' + btn));
}
});
});

How to change background colors between user input and computed output in javascript

Pretty new to javascript and jquery so I don't know if it's possible, but here goes. I'm attempting to build a simple chatbot feature for a website. Basically you click the help button link, a chatbox appears with a prompt for input. User inputs and a response comes out accordingly. I've got all this working fine.
What I want is to change the text color or background color of the user:"text" or help:"text" which alternate between chatting. Once the chatbox fills with back and forth text it becomes more difficult to differentiate between user input and feedback. Ideally i'd like the background color of chatbox feedback to be a gray color while user remains white.
HTML
<ul class="nav nav-pills nav-justified">
<li role="presentation" class="dropdown">
<a id="helpBtn" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
Help<span class="caret"></span></a>
<ul class="dropdown-menu">
<div id="helpBox">
<span id="usrText"></span>
</div>
<input id="textarea" placeholder="Type Here" maxlength="15">
</ul>
</li>
</ul>
JS/jquery
$(function() {
$('#helpBtn').click(function() {
$(this).toggleClass('active');
$('#helpBox').toggle();
$('#textarea').toggle();
if ($(this).hasClass('active')) {
$('#usrText').html('');
$('#usrText').append('HelpBot: What can I help you with? ','<br />'+'Please type "sales", "info" or "contact" for information.','<br />');
}
});
});
$(function() {
$('#textarea').keydown(function() {
var text = $(this).val();
if (event.keyCode == 13) {
$(this).val('');
$('text').css({
"background":"blue",
"color":"red"
});
$('#usrText').append('User: '+text,'<br />');
}
else {
return;
}
if (matches(text)==1) {
$('#usrText').append('HelpBot: Todays sales are: ','<br />');
}
else if (matches(text)==2) {
$('#usrText').append('HelpBot: Find info here: ','<br />');
}
else if (matches(text)==3) {
$('#usrText').append('HelpBot: Call: or Email: ','<br />');
}
else {
$('#usrText').append('HelpBot: I did not understand that. ','<br />');
$('#usrText').append('Please type "sales", "info", or "contact". ','<br />');
}
return false;
$('#helpBox').scrollTop($('#helpBox').children().height());
});
});
function matches(text) {
var a1 = ['sales','sale','bargain'];
var a2 = ['info','information','411'];
var a3 = ['contact','number','email','phone'];
var split = text.split(" ");
if (a1.includes(text)) {
var match = a1.includes(text);
return 1;
}
else if (a2.includes(text)) {
var match2 = a2.includes(text);
return 2;
}
else if (a3.includes(text)) {
var match3 = a3.includes(text);
return 3;
}
}
Here's the jsfiddle for the program:
JSfiddle Chatbot
If I understood you well, you want to change background color of HelpBot message? If that is the case then just add <span style="background-color:lightgray;">Your Text</span> and do it like this:
$(function() {
$('#helpBtn').click(function() {
$(this).toggleClass('active');
$('#helpBox').toggle();
$('#textarea').toggle();
if ($(this).hasClass('active')) {
$('#usrText').html('');
$('#usrText').append('<span style="background-color:lightgray;">HelpBot: What can I help you with? </span>', '<br />' + '<span style="background-color:lightgray;">Please type "sales", "info" or "contact" for information.</span>', '<br />');
}
});
});
$(function() {
$('#textarea').keydown(function() {
var text = $(this).val();
if (event.keyCode == 13) {
$(this).val('');
$('text').css({
"background": "blue",
"color": "red"
});
$('#usrText').append('User: ' + text, '<br />');
} else {
return;
}
if (matches(text) == 1) {
$('#usrText').append('<span style="background-color:lightgray;">HelpBot: Todays sales are: </span>', '<br />');
} else if (matches(text) == 2) {
$('#usrText').append('<span style="background-color:lightgray;">HelpBot: Find info here: </span>', '<br />');
} else if (matches(text) == 3) {
$('#usrText').append('<span style="background-color:lightgray;">HelpBot: Please call: (555)555-5555.', '<br /></span>', '<span style="background-color:lightgray;">HelpBot: Or you can email us at: wookiesRus#weirdos.net</span>', '<br />');
} else {
$('#usrText').append('<span style="background-color:lightgray;">HelpBot: I did not understand that. </span>', '<br />');
$('#usrText').append('<span style="background-color:lightgray;">Please type "sales", "info", or "contact". </span>', '<br />');
}
return false;
$('#helpBox').scrollTop($('#helpBox').children().height());
});
});
function matches(text) {
var a1 = ['sales', 'sale', 'bargain'];
var a2 = ['info', 'information', '411'];
var a3 = ['contact', 'number', 'email', 'phone'];
var split = text.split(" ");
if (a1.includes(text)) {
var match = a1.includes(text);
return 1;
} else if (a2.includes(text)) {
var match2 = a2.includes(text);
return 2;
} else if (a3.includes(text)) {
var match3 = a3.includes(text);
return 3;
}
}
#helpBtn {
color: black;
text-decoration: none;
}
#helpBox {
width: 100%;
height: 250px;
background-color: white;
overflow-y: auto;
display: none;
z-index: 1000;
}
#textarea {
position: absolute;
width: 100%;
margin-top: -23px;
display: none;
}
#usrText {
line-height: 1.4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul class="nav nav-pills nav-justified">
<li role="presentation" class="dropdown">
<a id="helpBtn" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
Help<span class="caret"></span></a>
<ul class="dropdown-menu">
<div id="helpBox">
<span id="usrText"></span>
</div>
<input id="textarea" placeholder="Type Here" maxlength="15">
</ul>
</li>

Tooltipster content doubling up each time it is opened

I'm using Tooltipster to show a list of items that the user can click so as to enter the item into a textarea. When a tooltip is created, I get its list of items with selectors = $("ul.alternates > li");
However, each time a tooltip is opened the item clicked will be inserted a corresponding number of times; for example if I've opened a tooltip 5 times then the item clicked will be inserted 5 times. I've tried deleting the variable's value after a tooltip is closed with functionAfter: function() {selectors = null;} but that had no effect.
I have a Codepen of the error here that should make it clearer.
// set list to be tooltipstered
$(".commands > li").tooltipster({
interactive: true,
theme: "tooltipster-light",
functionInit: function(instance, helper) {
var content = $(helper.origin).find(".tooltip_content").detach();
instance.content(content);
},
functionReady: function() {
selectors = $("ul.alternates > li");
$(selectors).click(function() {
var sampleData = $(this).text();
insertText(sampleData);
});
},
// this doesn't work
functionAfter: function() {
selectors = null;
}
});
// Begin inputting of clicked text into editor
function insertText(data) {
var cm = $(".CodeMirror")[0].CodeMirror;
var doc = cm.getDoc();
var cursor = doc.getCursor(); // gets the line number in the cursor position
var line = doc.getLine(cursor.line); // get the line contents
var pos = {
line: cursor.line
};
if (line.length === 0) {
// check if the line is empty
// add the data
doc.replaceRange(data, pos);
} else {
// add a new line and the data
doc.replaceRange("\n" + data, pos);
}
}
var code = $(".codemirror-area")[0];
var editor = CodeMirror.fromTextArea(code, {
mode: "simplemode",
lineNumbers: true,
theme: "material",
scrollbarStyle: "simple",
extraKeys: { "Ctrl-Space": "autocomplete" }
});
body {
margin: 1em auto;
font-size: 16px;
}
.commands {
display: inline-block;
}
.tooltip {
position: relative;
opacity: 1;
color: inherit;
}
.alternates {
display: inline;
margin: 5px 10px;
padding-left: 0;
}
.tooltipster-content .alternates {
li {
list-style: none;
pointer-events: all;
padding: 15px 0;
cursor: pointer;
color: #333;
border-bottom: 1px solid #d3d3d3;
span {
font-weight: 600;
}
&:last-of-type {
border-bottom: none;
}
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.2/theme/material.min.css" rel="stylesheet"/>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/235651/jquery-3.2.1.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/235651/tooltipster.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.2/codemirror.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.2/addon/mode/simple.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.2/addon/hint/show-hint.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.2/addon/scroll/simplescrollbars.js"></script>
<div class="container">
<div class="row">
<div class="col-md-6">
<ul class="commands">
<li><span class="command">Hover for my list</span><div class="tooltip_content">
<ul class="alternates">
<li>Lorep item</li>
<li>Ipsum item</li>
<li>Dollar item</li>
</ul>
</li>
</div>
</ul>
</div>
<div class="col-md-6">
<textarea class="codemirror-area"></textarea>
</div>
</div>
</div>
Tooltipster's functionReady fires every time the tooltip is added to the DOM, which means every time a user hovers over the list, you are binding the event again.
Here are two ways to prevent this from happening:
Attach a click handler to anything that exists in the DOM before the tooltip is displayed. (Put it outside of tooltipspter(). No need to use functionReady.)
Example:
$(document).on('click','ul.alternates li', function(){
var sampleText = $(this).text();
insertText(sampleText);
})
Here's a Codepen.
Unbind and bind the event each time functionReady is triggered.
Example:
functionReady: function() {
selectors = $("ul.alternates > li");
$(selectors).off('click').on('click', function() {
var sampleData = $(this).text();
insertText(sampleData);
});
}
Here's a Codpen.
You are binding new clicks every time.
I would suggest different code style but in that format you can just add before the click event
$(selectors).unbind('click');
Then do the click again..

Custom html tab implementation problems

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();
}

How to make a tooltip for incoming list items

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

Categories