Using razor to build a popup tooltip menu - javascript

I am having a problem with dynamically generating this dropdown menu. This works if I'm not making it dynamically.
The #t.Id is working and is different every time in the loop. I'm pretty sure its the first line that's wrong as I have used the id="" before this way.
<b>tagged</b>
<div style="display: none;">
<div id="tagsdiv#(t.Id)">
<span class="menu">hhhh<br />
nnnn
#for( int i = 0; i < t.tTags.Count; i++ ) {
<b>#Html.ActionLink( t.tTags[i], "TagDetail", "Forums", new { tag = t.tTags[i], page = 0 }, null )</b>
}
</span>
</div>
</div>

Tips to debug Razor (or any server-side code rendering markup) more effectively:
View the rendered HTML! is it correct?
Remove styles/scripts until you are sure the server is rendering the values you want.
Add a breakpoint to your controller to make sure you are passing data to the view. Your rendering logic may be fine.
That said, your code appears to work fine. I dummied up some data:
#{ var t = new { Id = 1234, tTags = new List<string> { "foo", "bar", "baz" } }; }
<b>tagged</b>
<div style="display: none;">
<div id="tagsdiv#(t.Id)">
<span class="menu">
#for( int i = 0; i < t.tTags.Count; i++ ) {
<b>#Html.ActionLink( t.tTags[i], "TagDetail", "Forums", new { tag = t.tTags[i], page = 0 }, null )</b>
}
</span>
</div>
</div>
This yields:
<b>tagged</b>
<div style="display:none;">
<div id="tagsdiv1234">
<span class="menu">
<b>foo</b>
<b>bar</b>
<b>baz</b>
</span>
</div>
</div>
One thing that really looks wrong here is '#tagsdiv1234'. Are you sure your tooltip needs an ID including the CSS/jQuery ID selector ("#")?
Another thing that stands out is your tooltip container is wrapped with an outer div set to display:none. The ID'd element will always be hidden because its parent is hidden, even if the tooltip code tries to show it.
Another possibility is that your ID contains a character illegal in an element identifier.

Related

How to edit childrens div?

I have this HTML code (and the number of components that I want to edit it's variable, it could be 3 or 20).
I have created a small example with similar scenario on my website
As you can see my script is able to edit the father div and add the classname. Same for firstchild.
I would like to edit all divs inside firstchild but not the immediately div, it has to be two inside.
Any ideas why my code is not working on the last part?
Thanks.
// WORKS OK
var firstc = document.getElementById('father');
firstc.classList.add("father-class");
firstc.children[0].children[0].children[0].setAttribute("id", "firstchild"); // WORKS OK
var second = document.getElementById('firstchild');
second.classList.add("child-class");
// NOT WORKING
var grandchildren = second.children[0].children[0].children[0];
for (let z = 0; z < grandchildren.length; z++) {
grandchildren[z].classList.add("slide");
}
<div id="father">
<div>
<div>
<div id="firstchild">
<div>
<div>
<div class="random63637236">
<li>1</li>
</div>
<div class="generic">
<li>2</li>
</div>
<div class="italy_gdgd">
<li>3</li>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
the problem in your code is the last children[0]. you are selecting only the first div, it's not an array. Fix that line and everything will work
var grandchildren = second.children[0].children[0].children;
As a side note: if for some reason the first or the second .children[0] are undefined you will get an error.
A better approach is to use querySelectorAll which returns an array;
if your array it is empty, nothing happens.
second.querySelectorAll('#firstchild > div > div > div')
.forEach(el => el.classList.add('slide'))

Issues with find() when inserting html dynamically using jquery

I have a modal with a grid of buttons representing different html components. When one of the buttons is pressed, some html is supposed to be injected into the page once the modal closes. However, I'm having trouble targeting the specific column where the html is to be injected. Here's my code:
<div class="row" id="newRow">
<div class="col-md-12 column">
<button class="btn addElement" href="#" data-toggle="modal" data-target="#add-element"><i class="fa fa-plus fa-3x add-item"></i></button>
</div>
</div>
And in my js file I have some code to assign an id to the column div (since there could potentially be many columns with this addElement button) that looks like this:
...
$(this).parent().next().children().find('.column').assignId();
...
Up to this point, everything works well. I'm having no trouble getting the column a unique id (defined in my assignId() function).
As I mentioned, the addElement button gets clicked, opening a modal which is when this code is executed:
$(document).on('click', 'button.addElement', function (e) {
e.preventDefault();
$('#add-element').modal('show').draggable();
var col = $('button.addElement').parent();
// debugging in the browser verifies that the colId
// successfully stores the id attribute for the column
var colId = col.attr('id');
addElements(colId);
});
...
function addElements(colId) {
$('#insert-paragraph').on('click', function () {
var html_content = '<div class="box" data-type="paragraph">...</div>';
$("#newRow").find("#"+colId).html(html_content)
$('#add-element').modal('hide');
});
}
It's on this line: $("#newRow").find(colId).html(html_content); that I'm having the issue. My guess is that the formatting for find(...) is wrong and that I can't just insert a variable like that, but I've tried a few different things and nothing seems to be working.
Any help is very much appreciated.
Thanks!
UPDATE:
#juvian suggested writing a few of the variables' values to the console:
console.log(colId);
console.log($("#newRow")).length;
console.log($("#newRow").find("#"+colId).length);
console.log($("#newRow").find("#"+colId).html());
I logged these values twice. First, just before passing colId into the addElements function and in the addElements function immediately after $(#newRow").find("#"+colId).html(html_content); The results of those two tests are as follows:
Values prior to running addElements:
console.log(colId); = 8153-1076-641d-3840
console.log($("#newRow")).length; = Object[div#newRow.row.clearfix]
console.log($("#newRow").find("#"+colId).length); = 1
console.log($("#newRow").find("#"+colId).html()); = <button class="btn addElement"...>...</button>
Values after the insert-paragraph button is pressed:
console.log(colId); = 8153-1076-641d-3840
console.log($("#newRow")).length; = Object[div#newRow.row.clearfix]
console.log($("#newRow").find("#"+colId).length); = 1
console.log($("#newRow").find("#"+colId).html()); = <div class="box box-element" data-type="paragraph">...</div>
Interestingly enough, it appears like everything is working like I'd expect it to, however, when it's all said and done, the addElement button remains and the page still renders this:
<div id="newRow" class="row clearfix">
<div id="32aa-ab91-f50d-c3b3" class="col-md-12 column ui-sortable">
<button class="btn addElement" data-target="#add-element" data-toggle="modal" href="#">
<i class="fa fa-plus fa-3x add-item"></i>
</button>
</div>
</div>
.find as most jquery functions, takes a css selector as parametre. Unfortunately, colId is just a string, so it matches no elements (unless colId is html, span or something like that)
You are just missing adding the id selector at the beginning to do an id match:
.find("#"+colId)
I guess The parent of button is a div here which has no id.
var col = $('button.addElement').parent();
thus var colId is getting no value.give that div an id and it should be fine.

jQuery Replicate an existing Div Multiple Times

I am building a search query which gives me results.
I have a template ready for the item inside a hidden div. What I want to do is replicate the template n number of times using jQuery.
So For example:
I search for flights and I get 5 search results, I need to replicate the below div template 5 Times
<div id="oneWayFlightElement" class="displayNone">
<div id="flightIndex1" class="flightDetailElement boxShadowTheme">
<div id="flightDetailsLeftPanel1" class="flightDetailsLeftPanel marginBottom10">
<div class="fullWidth marginTop10">
<span id="flightPriceLabel1" class="headerFontStyle fullWidth boldFont">Rs 9500.00</span><hr/>
<div id="homeToDestination1" class="flightBlockStyle">
<span id="flightNumberFromHome1" class="fontSize16">AI-202</span><br/>
<span id="flightRouteFromHome1" class="fontSize26">PNQ > DEL</span><br/>
<span id="flightDepartTimeFromHome1" class="fontSize26">Depart: 10.00 AM</span><br/>
<span id="flightArrivalTimeFromHome1" class="fontSize26">Arrive: 12.00 PM</span><br/>
</div>
<div id="destinationToHome1" class="flightBlockStyle">
<span id="flightNumberToHome1" class="fontSize16">AI-202</span><br/>
<span id="flightRouteToHome1" class="fontSize26">PNQ > DEL</span><br/>
<span id="flightDepartTimeToHome1" class="fontSize26">Depart: 10.00 AM</span><br/>
<span id="flightArrivalTimeToHome1" class="fontSize26">Arrive: 12.00 PM</span><br/>
</div>
</div>
</div>
<div id="flightDetailsRightPanel1" class="flightDetailsRightPanel textAlignRight marginBottom10">
<img src="images/flightIcon.png" class="marginRight10 marginTop10 width40"/><br/>
<button class="marginRight10 marginBottom10 width40 bookNowButtonStyle">Book Now</button>
</div>
</div>
</div>
Inside this div for 5 times
<div id="searchFlightResultDiv" class="fullWidth" style="border:solid">
</div>
Is there a better way to do that rather than string appending in jQuery?
Thanks,
Ankit Tanna
You'll need to wrap your template div (#flightIndex1) in a container with a unique id attribute. Then, you take the contents of that container (a template for a single record), and append it to your results div (#searchFlightResultDiv) using some type of loop based on the number of results received.
Basically,
HTML:
<!-- Here's your template -->
<div class="displayNone" id="oneWayFlightElement">
<!-- This id (singleResult) is important -->
<div id="singleResult">Result</div>
</div>
<!-- Container for the results -->
<div id="results"></div>
Javascript:
//Get the number of results.
//This can be sent from your API or however you're getting the data.
//For example, in PHP you would set this to $query->num_rows();
var count = 5;
//Start a for loop to clone the template element (div#singleResult) into div#results 'count' times.
//This will repeat until the number of records (count) has been reached.
for (i = 1; i <= count; i++) {
//Append the HTML from div#thingToRepeat into the #results.
$('#results').append($('#singleResult').clone());
}
Here's a JSFiddle to show you how it works. You can play with it and tweak it if necessary.
I can't in good conscious complete this post without telling you the downsides of this. Doing it this way is majorly frowned upon in the web development community and is super inefficient. It may be good for practice and learning, but please do take a look at and consider a javascript templating framework like moustache or handlebars. It does this same thing but way more efficiently.
Hope this was helpful!
function populateResult(resCount) {
resCount = typeof resCount === 'number' ? resCount : 0;
var res = [];
var templateEle = $('#oneWayFlightElement');
for(var i = 0; i < resCount; ++i)
res.push(templateEle.clone().removeAttr('id class')[0]);
$('#searchFlightResultDiv').html(res);
}
populateResult(5);
We use an array res to hold the DOM elements as we loop and finally sets it to the target div using html method. We don't need a JQuery object here as the html method accepts any array like object. In this way we can minimize browser reflows. Here is the JSFiddle

Hiding divs whenever a new one opens

I have a website with two options represented by <a> tags, chairs and tables. This is the HTML that displays the div whenever a <a> tag is clicked on.
<div id="workbench_menu">
<p><strong>Living Room</strong></p>
<a onclick="chairs()" href="#"><p>chairs</p></a>
<a onclick="tables()" href="#"><p>tables</p></a>
</div>
<div id="workbench_objects">
<div id="tables" class="refresh" style="display:none;">
<div class="workbench_object_info">
<img src="images/house/objects/table_4.png">
<p>20 oak logs</p>
</div>
</div>
<div id="chairs" class="refresh" style="display:none;">
<div class="workbench_object_info">
<img src="images/house/objects/stonechair_1.png">
<p>20 oak logs</p>
</div>
</div>
</div>
The javascript which handles that function is here:
<script>
function tables() {
document.getElementsByClassName('refresh').style.display='none';
document.getElementById('tables').style.display='inline';
}
function chairs() {
document.getElementsByClassName('refresh').style.display='none';
document.getElementById('chairs').style.display='inline';
}
</script>
So what I am trying to do, is that when one of the options are pressed, everything else is hidden and only the div that is assigned that specific <a> tag will be displayed. When a new <a> tag is clicked, the old one will be hidden and the new on will be displayed.
I have tried adding a document.getElementsByClassName('refresh').style.display='none'; in hope that every class with "refresh" attached to it, will be put on display:none but this does not work somehow. The outcome is that after a link is clicked, the div is shown. After a new link is clicked, that div is shown too without hiding the old div. Hope you have some suggetions, thanks in advance.
UPDATE:
var length = document.getElementsByClassName('refresh').length;
for(var i=0; i<length;i++){
document.getElementsByClassName('refresh')[i].style.display='none';
}
function tables() {
document.getElementById('tables').style.display='inline';
}
function chairs() {
document.getElementById('chairs').style.display='inline';
}
document.getElementsByClassName('refresh') will return you the array of elements.
function tables() {
hideElements();
document.getElementById('tables').style.display='inline';
}
function chairs() {
hideElements();
document.getElementById('chairs').style.display='inline';
}
function hideElements(){
var length = document.getElementsByClassName('refresh').length;
for(var i=0; i<length;i++){
document.getElementsByClassName('refresh')[i].style.display='none';
}
}

Dynamic div content + retain last viewed div on browser backward

I am using dynamic div content and toggling between them on clicks, works well but is there a way to retain the last viewed div when the user clicks forward and backward on his browser? Thanks.
<script>
$(".settings").click(function() {
var id = this.id;
if ($("." + $(this).attr('rel')).css('display') == 'none') {
$('.n_tab').hide();
$('.p_tab').hide();
($("." + $(this).attr('rel')).show());
}
});
</script>
<div class="settings" rel="n_tab">
<div class="title info_2_Title">
Notifications</div>
</div>
<div class="settings" rel="p_tab">
<div class="title info_2_Title">
Privacy</div>
</div>
<div id="MasterContainer">
<div class="n_tab" style="display: none;"> the N DIV </div>
<div class="p_tab" style="display: none;"> the P DIV </div>
</div>
Try using a library like history.js to set that up. Internally it will use the pushState API, or fall back to url fragments if the browser doesn't support that.
You could try adding an id to each tab and appending that in an object or array each time a div is selected.
Define an array history = []; outside the click event and in your click event something like
history.push($(this).id);
If you wanted to keep more detailed data you could use a json object and append to it.
Thanks for the help guys, but after fiddling ard with History.js, I still couldn't get it to work, in the end I used a cookie to store the state and then check it when the page with dynamic div loads.
$(function() {
var x = $.cookie('tab_cookie');
($(x).show());
if (x == '.m_tab') {
var btn = document.getElementById('<%= btnLoadm.ClientID %>');
if (btn) btn.click();
}
});

Categories