To build a menu block which should be switchable with hide/unhide of the menu items, I'm using .append html.
The code idea is this:
navigat += '<h3 class="infoH3"> <a id="' + menuID +'"'
+ ' href="javascript:slideMenu(\'' + menuSlider + '\');">'
+ menuName + '</a></h3>';
navigat += '<div id="' + menuSlider + '" style="display:none">';
navigat += ' <ul>';
navigat += ' <li>aMenu1</li>'
navigat += ' <li>aMenu2</li>'
navigat += ' <li>aMenu3</li>'
navigat += ' </ul>';
navigat += '<!-- menuName Slider --></div>';
$("#someElement").append (navigat);
This is doing well .. so far.
But the point is::
I use JS to read the required menu items (eg. 'aMenu1' together with title and/or link info) from a file to build all that, eg. for 'aMenu1' a complex is composed and $("#someElement").append(someString) is used to add that the 'someElement'.
At the moment I build those html elements line by line. Also OK .. as far as the resulting string has the opening and closing tag, eg. "<li>aMenu2</li>".
As can be seen from above posted code there is a line "<div id="' + menuSlider + '" style="display:none">".
Appending that -- AFAIS -- the .append is automatically (????) adding "</div>" which closes the statement.
That breaks my idea of the whole concept! The menu part isn't included in the 'menuSlider '.
QQ: How to change it -- NOT to have that "</div" added to it??
Günter
You could change you method around to use document fragment style creation and an object to populate the properties on the elements, like this:
var someElement = $("#someElement");
$('<h3 class="infoH3"></h3>').append($('<a />',
{ 'id': menuID,
'href': '#',
click: function() { slideMenu(menuSlider); }
})
).appendTo(someElement);
var div = $('<div />', { 'id': menuSlider, css: {display: 'none'} });
$('<ul />').append('<li>aMenu1</li>')
.append('<li>aMenu2</li>')
.append('<li>aMenu3</li>')
.appendTo(div);
div.appendTo(someElement);
This is a very different way of doing it, first we're caching the $("#someElement") object so we're not searching for it repeatedly. Then we're creating the <h3> as an object, putting the link inside, then inserting then appending the whole thing to someElement. In the last, the same approach it's creating the <div>, setting it's properties, then creates the <ul> menu and appends it inside...then appends that whole div to someElement as well.
As a side note, I'm not sure how .slideMenu() works, but an event handler that works via $(this).parent().next() (or give the div a class) would work as well, and you wouldn't need a function with the slider argument passed.
Related
I'm working on a website that makes a call to a database. It takes the JSON from the database and loops through a specific node -- appending HTML code to a div tag, which creates a Card for each database entry. I want to be able to have a Bootstrap Popover (or Tooltip) that appears when a Card is clicked (or hovered over if Tooltip). The Cards that are generated within the function fail to produce a Popover or Tooltip at all. If I append the same HTML code outside the function using JQuery, it works just fine. I'm unsure what is happening here.
Here's the function that loops through the database JSON and creates a card for each child.
function getWeekEvents(day, id) {
return firebase.database().ref(day).once('value').then(function(snapshot) {
var data = snapshot.val();
for (item in data) {
var event = data[item]["event"];
var loc = data[item]["loc"];
var time = data[item]["time"];
$("#" + id).append("<div class='card border border-primary week-cards-ann event-style' data-toggle='popover' data-content='Content' data-placement='right'>" +
"<div class='card-body my-lg-n3'>" +
"<div class='card-text my-lg-n1 float-left ml-lg-n3'>" +
"<p>" + event.substring(0,10) + "...</p>" +
"</div>" +
"</div>" +
"</div>");
}
});
}
The code below is outside any function and works just fine. It creates a card in the same way, but the Popover works.
$("#tuesday").append("<div class='card border border-primary week-cards-ann event-style' data-toggle='popover' data-placement='top' title='Hello'>" +
"<div class='card-body my-lg-n3'>" +
"<div class='card-text my-lg-n1 float-left ml-lg-n3'>" +
"<p>" + "...</p>" +
"</div>" +
"</div>" +
"</div>");
And I also have this part that is required for Popovers to work.
$(function () {
$('[data-toggle="popover"]').popover()
});
I also tried creating a Tooltip in the same way, instead of a Popover, but it resulted in the same problem. This lead me to believe that there may be something happening with the data-toggle attribute? I could be wrong. Does anyone have any thoughts?
I am trying to create a dynamic navigation which adds elements to a standard bootstrap navigation with the following code:
// Map item to the navigation
function addToNavigation (navigationItem) {
// Build the navigation item HTML string
var navigationItemHTML = '<li><a';
if(navigationItem.dataTarget){ navigationItemHTML += ' data-target="#' + navigationItem.dataTarget + '" data-toggle="collapse"';}
navigationItemHTML += ' aria-expanded="false" class="pointer">';
if(navigationItem.icon){ navigationItemHTML += '<span class="glyphicon glyphicon-' + navigationItem.icon + '></span> ';}
navigationItemHTML += navigationItem.title + '</a></li>';
// Append the new item to the navigation
$('#navigation').append(navigationItemHTML);
}
If I set a breakpoint the contents of "navigationItemHTML" appear exactly how I want them however the result on the page omits the navigation item title and the optional glyphicon.
Why is this and is there a better way of accomplishing what I want to achieve in jQuery/JavaScript?
Managed to figure out it was a problem with the string I was trying to pass to jQuery, I had more luck instantiating each tag as an element within the last:
// Map item to the navigation
function addToNavigation (navigationItem) {
// Build the navigation item HTML string
var navigationItemHTML = $('<li></li>').html(
$('<a></a>').html(
$('<span></span>').html(
' ' + navigationItem.title).prepend(
$('<span><span>').addClass('glyphicon glyphicon-' + navigationItem.icon)))
.attr('data-target', '#' + navigationItem.dataTarget)
.attr('data-toggle', 'collapse').addClass('pointer'));
// Append the new item to the navigation
$('#navigation').append(navigationItemHTML);
}
I still think this looks abit messy however, please let me know if anyone finds a more elegant solution.
I'm making a Carnival calendar for my city.
I'm using this as a basic calendar engine: https://github.com/jlord/sheetsee-calendar
For a basic Modal i'm using this: https://github.com/FinelySliced/leanModal.js
I want to be able to click on the event and put it to show some information about it: name, time and place.
var eventElement = $('<div class="event"><a class="' +
event.location + '" href="#informa" rel="leanModal" >' +
event.name + "#" + event.tickets +
'</a></div> <div id="informa"> <p>' +
event.name + '</p></div>')
I made a test modal in the index.html and it worked, but it is not working when i try to do this.
You have created an element, but haven't added it to the DOM of the page.
try something like
$('body').append(eventElement);
as the next line.
I have a similar question in which I didn't have the right data in a fiddle to show. What the other question shows is doing a table row clone, but my data is table append to a div
The jQuery $.each loop shows where I have a dynamically created the title (tooltip)
This is the fiddle: http://jsfiddle.net/bthorn/Lpuf0x7L/1/
$.each(allData, function (index, issues) {
strResult += "<tr><td class='nameField'> <a href='#'>" + issues.LAST_NAME + " " + issues.FIRST_NAME + " " + issues.INITIALS + "</a></td><td>" + issues.OFFICE + "</td><td>" + issues.TITLE + "</td>";
strResult += "<td>" + issues.DEPARTMENT + "</td><td class='alias'>" + issues.ALIAS_NAME + "</td>";
// NEED TO ADD QTIP to the issues.DEPARTMENT title tooltip //////
addTooltips();
/////////
strResult += "</tr>";
});
strResult += "</table>";
$("#divEmpResult").html(strResult);
My old question from a few hours with OP answer should be helpful
dynamic javascript data with qtip is overriding all tooltips with same message
I am trying to call this function but i know that I needs to have additional data from qtip appended to it.
OP was doing a .insertBefore(this) but I am not sure how to do that with my table row
$('button').on('click', function() {
$('<div/>', {
class: 'tips',
text: 'Dynamically inserted.'
}).insertBefore(this);
addTooltips();
In the second code snippet, the addTooltips function was called after the dynamic element(s) were inserted into the DOM via the .insertBefore() method.
In your first code snippet, you are calling the addTooltips function before the elements are actually appended, which is why it isn't working as expected:
$("#divEmpResult").html(strResult);
addTooltips(); // Call the function *after* the elements exist in the DOM
In order to prevent the previous tooltips from being overridden, negate all the elements with data-hasqtip attributes. You can also set the tooltip text based on the title attribute, or some pre-defined defaults like in the example below:
$('.tips:not([data-hasqtip])').each(function() {
$(this).qtip({
content: {
text: $(this).attr('title') || 'This is the message!'
},
hide: {
fixed: false
},
position: {
corner: {
target: 'topLeft',
tooltip: 'bottomRight'
}
}
});
});
To address your last issue where the tooltips only included the first word, you need to enclose the title attribute value in quotes. Previously, your HTML was being rendered like: title=some words here, which resulted in the browser automatically inserting quotes around the first white-space separated word and turning the following words into separate attributes.
Working Example Here
The title attribute value needs to be enclosed in quotes:
strResult += '<td class="tips" title="' + issues.DEPARTMENT + '">' + issues.DEPARTMENT + '</td><td class="alias">' + issues.ALIAS_NAME + '</td>';
To avoid mistakes like this, I would highly suggest using a JS templating engine such as handlebars.
I know that there's lot here on already on multiple click events being fired off, I think I've read them all but still can't see what's going wrong here.
Hope fully I'm missing something obvious that someone else can pick up easily...
Some background
My code works inside an Enterprise Social Networking platform and creates a BI dashboard for content analysis (about a 1000 lines of the stuff, mostly domain specific, so too much to post in it's entirety).
The part that is causing me grief is the function that builds the dashboard visualisation itself.
Here goes...
function makePage(){
$("#policyCount").text(policyCount);
var docTypes=getGlobalDocTypes(polOwners); //returns a constrained vocab array
var statusTypes=getGlobalStatusTypes(polOwners); //returns a constrained vocab array
$.each(polOwners,function(){ // polOwners is a global array that contains the BI data to be visualised
html=""
var ownerName = this.name.split(":")[1]; // name is a str in format "Owner:HR"
html += "<div id='" + ownerName + "' class='ownerData'>";
html += "<div class='ownerHeading'>" + ownerName + "</div>";
html += this.policies.length + " Policy documents maintained<br />"; // policies is an array of docs managed by owner
divIDReview = "dboard_" + ownerName + "reviewchart";
html += "<div id='" + divIDReview + "' class='dboardelement'></div>";
divIDType = "dboard_" + ownerName + "typechart";
html += "<div id='" + divIDType + "' class='dboardelement'></div>";
divIDStatus = "dboard_" + ownerName + "statuschart";
html += "<div id='" + divIDStatus + "' class='dboardelement'></div>";
html += "<div id='" + ownerName + "ToggleTable' class='toggletable' owner='" + ownerName + "'>";
html += "Click to display all " + ownerName + " documents<br /></div>";
html += "<div id='" + ownerName + "polTable' class='poltable'>";
html += getPolTable(this.policies); // Returns an HTML table of doc metadata
html += "</div>";
html += "</div>";
$("#owners").append(html); // When this function is called #owners is an empty div
$(".toggletable").mouseover(function(){
$(this).css({'cursor':'pointer','text-decoration':'underline'});
});
$(".toggletable").mouseout(function(){
$(this).css( {'cursor':'default','text-decoration':'none'});
});
$(".toggletable").each(function(i, elem){
$(elem).click(function(){
if ($(this).next(".poltable").css("display")=="none"){
// Currently hidden - so show
if (debug){console.log($(this).attr("id") + " was clicked")}
$(this).html("Click to hide " + $(this).attr('owner') + " documents<br/>");
$(this).next(".poltable").css("display","block");
} else {
if (debug){console.log($(this).attr("id") + " was clicked")}
$(this).html("Click to display all " + $(this).attr('owner') + " documents<br />");
$(this).next(".poltable").css("display","none");
}
});
});
// the next section calls functions that use the Google vis api to draw pie charts
drawPie(300,200, "Review Status", "Status", "Policies", getReviewStatus(this.policies), ["green","orange","red"], divIDReview);
drawPie(300,200, "Document Types", "Type", "Docs", getDocTypes(this.policies, docTypes), [], divIDType);
drawPie(300,200, "Document Status", "Status", "Docs", getStatusTypes(this.policies, statusTypes), [], divIDStatus);
});
}
Hopefully that's enough to illustrate the problem.
You'll see that the code builds a dashboard display for each polOwner consisting of three pie charts and an option to hide or display a table of underlying data.
I started by applying the click event to the .toggletable class. When that fired multiple times I used the method described on another answer here with the .each to attach a unique event to each instance of the class.
So, what happens?
There are currently 9 polOwners and at first glance, the click event only seems to be toggling the display state of every other table. The console log however shows that this is because it is firing 9 times for the first instance, 8 for the second, 7 for the third etc. with the odd numbers leaving the table in the alternate state (when this works the display will change to a .toggle animation).
For info, While I'm a text editor person, I do have a copy of MS Expression Web 4 which is a useful tool for error checking HTML. I've pasted in a copy of the entire generated markup (nearly 4000 lines) and can't see any bad nesting or structure errors.
Any ideas folks?
You've got some nested loops:
// jQuery each on polOwners
$.each(polOwners,function(){
// ... code that appends .toggletable class
// jQuery each on .toggletable class
$(".toggletable").each(function(i, elem){
// code that runs on the toggletable element
});
});
For each polOwner you are adding a div with the toggletable class. Then inside there you are looping through each div with a toggletable class and adding a click event.
This adds 1 click for the first polOwner, 2 for the second, three for the third and so on.
Move the toggletable each outside of the polOwner each and you should be good