Define a scope in directive and use it in a view - javascript

I am using angular-treeview directive. Here , It is taking some time to load the tree, so I want to show a spinner for that time. So, I want to define a variable in directive and that will be used in the view so that I can show a spinner.
**angular-treeview.js**
(function ( angular ) {
'use strict';
angular.module( 'angularTreeview', [] ).directive( 'treeModel', ['$compile', function( $compile) {
return {
restrict: 'A',
link: function ( scope, element, attrs ) {
//tree id
var treeId = attrs.treeId;
//tree model
var treeModel = attrs.treeModel;
//node id
var nodeId = attrs.nodeId || 'id';
//node label
var nodeLabel = attrs.nodeLabel || 'label';
//node class
var nodeClass = attrs.nodeClass || 'type';
//children
var nodeChildren = attrs.nodeChildren || 'children';
//search by label
var searchQuery = attrs.searchQuery || '';
//function for highlighting search text
var searchHighlightFunction = attrs.searchHighlightFunction ||
function (content, text) {
return content
};
//css class to be added for highlighting
var searchHighlightClassName = attrs.searchHighlightClassName || '';
//filter to be used with search query
var searchFilter = attrs.searchFilter || '';
//tree template
var template =
'<ul>' +
'<li data-ng-repeat="node in ' + treeModel + '| ' + searchFilter + ':' + searchQuery + '" data-ng-init="node.collapsed=true">' +
'<i class="collapsed {{node.' + nodeClass + '}}" data-ng-show="node.' + nodeChildren + '.length && node.collapsed" data-ng-click="' + treeId + '.selectNodeHead(node)"></i>' +
'<i class="expanded {{node.' + nodeClass + '}}" data-ng-show="node.' + nodeChildren + '.length && !node.collapsed" data-ng-click="' + treeId + '.selectNodeHead(node)"></i>' +
'<i class="normal {{node.' + nodeClass + '}}" data-ng-hide="node.' + nodeChildren + '.length"></i> ' +
'<span data-ng-class="node.selected" data-ng-click="' + treeId + '.selectNodeLabel(node)" ' +
'ng-bind-html="' + searchHighlightFunction + '(node.' + nodeLabel + ', ' + searchQuery + ', \'' + searchHighlightClassName + '\', true)"></span>' +
'<div data-ng-hide="node.collapsed" data-tree-id="' + treeId + '" data-tree-model="node.' + nodeChildren +
'" data-node-id=' + nodeId + ' data-node-label=' + nodeLabel + ' data-node-children="' + nodeChildren + '"' +
' data-node-class="' + nodeClass + '" data-search-query="' + searchQuery + '" data-search-highlight-function="' + searchHighlightFunction + '"' +
' data-search-highlight-class-name="' + searchHighlightClassName + '" data-search-filter="' + searchFilter + '"></div>' +
'</li>' +
'</ul>';
//check tree id, tree model
if( treeId && treeModel ) {
/*
* to expand or collapse nodes on search text changes
*/
scope.$watch(searchQuery, function (newVal, oldVal) {
var node = scope.node;
if (newVal) {
if (newVal.length > 0) {
if (node) {
if ((node[nodeChildren] && node[nodeChildren].length)
|| (node[nodeChildren] && node[nodeChildren].length)) {
node.collapsed = false;
}
}
}
} else {
if (node && ((node[nodeChildren] && node[nodeChildren].length)
|| (node[nodeChildren] && node[nodeChildren].length))) {
node.collapsed = (scope[treeId].expandedNodes.indexOf(node[nodeLabel]) < 0);
}
}
});
//root node
if( attrs.angularTreeview ) {
//create tree object if not exists
scope[treeId] = scope[treeId] || {};
//this is where we are storing nodes by user to distinguish between
// those expanded by user from those done for showing search results
scope[treeId].expandedNodes = [];
scope.$watch(treeModel, function(newVal, oldVal) {
if (newVal) {
scope[treeId].expandedNodes = [];
}
});
//if node head clicks,
scope[treeId].selectNodeHead = scope[treeId].selectNodeHead || function( selectedNode ){
var expandedNodesIndex;
//Collapse or Expand
selectedNode.collapsed = !selectedNode.collapsed;
expandedNodesIndex = scope[treeId].expandedNodes.indexOf(selectedNode[nodeLabel]);
if (expandedNodesIndex > -1) {
if (selectedNode.collapsed) {
scope[treeId].expandedNodes.splice(expandedNodesIndex, 1);
}
} else {
if (!selectedNode.collapsed) {
scope[treeId].expandedNodes.push(selectedNode[nodeLabel]);
}
}
};
//if node label clicks,
scope[treeId].selectNodeLabel = scope[treeId].selectNodeLabel || function( selectedNode ){
//remove highlight from previous node
if( scope[treeId].currentNode && scope[treeId].currentNode.selected ) {
scope[treeId].currentNode.selected = undefined;
}
//set highlight to selected node
selectedNode.selected = 'selected';
//set currentNode
scope[treeId].currentNode = selectedNode;
};
}
//Rendering template.
element.html('').append( $compile( template )( scope ) );
}
}
};
}]);
})( angular );
My html is -
<div data-angular-treeview="true" data-tree-id="Treevalue"
data-tree-model="suggestionList" data-node-id="id" data-node-class="type" data-node-label="name"
data-node-children="childrens" data-search-query="suggestionListSearchText" data-search-highlight-function="highlightHTML"
data-search-highlight-class-name="searchText" data-search-filter="NameFilter">
</div>
So, How to define a variable in this directive and use it in the scope ?

Looking through the code, it may be as simple as adding HTML inside the div with data-tree-view on it. That HTML will be wiped as part of the tree view directive, so anything you add in there (like a spinner) will be displayed until the directive finishes.
Edit:
Add an image inside the tree view div. This HTML will be cleared, so it will only show while it's loading.
<div data-angular-treeview="true" data-tree-id="Treevalue"
data-tree-model="suggestionList" data-node-id="id" data-node-class="type" data-node-label="name"
data-node-children="childrens" data-search-query="suggestionListSearchText" data-search-highlight-function="highlightHTML"
data-search-highlight-class-name="searchText" data-search-filter="NameFilter">
<img src="spinner.gif">
</div>

Related

FacetWP: Show labels only if facet has options

I want to show labels only if the facet has any options. Therefore I tried the following code:
<script>
(function($) {
$(document).on('facetwp-loaded', function() {
$('.facetwp-facet').each(function() {
var facet_name = $(this).attr('data-name');
var facet_label = FWP.settings.labels[facet_name];
if ($('.facet-label[data-for="' + facet_name + '"]').length < 1 && $(this).children()
.length > 0) {
$(this).before('<p class="h5 facet-label" data-for="' + facet_name + '">' + facet_label + '</p>');
}
});
});
})(jQuery);
</script>
It works but only if I reload the page with active filters.
If I change the filter, the labels stay.
Is there any option to ask if the are a new filters after a click?
The plugin author gave me an hint for a solution:
<script>
(function($) {
$(document).on('facetwp-loaded', function() {
$('.facetwp-facet').each(function() {
var facet_name = $(this).attr('data-name');
var facet_label = FWP.settings.labels[facet_name];
if ( 'undefined' !== typeof FWP.settings.num_choices[facet_name] && FWP.settings.num_choices[facet_name] > 0 && $('.facet-label[data-for="' + facet_name + '"]').length < 1 ) {
$(this).before('<h3 class="facet-label" data-for="' + facet_name + '">' + facet_label + '</h3>');
} else if ( 'undefined' !== typeof FWP.settings.num_choices[facet_name] && !FWP.settings.num_choices[facet_name] > 0 ) {
$('.facet-label[data-for="' + facet_name + '"]').remove();
}
});
});
})(jQuery);
</script>

Concatenation javascript error -probably simple to fix

I'm trying to do the next thing:
getChatListMessageString: function(dateObject, userID, userName, userRole, messageID, messageText, channelID, ip) {
var rowClass = this.DOMbufferRowClass,
userClass = this.getRoleClass(userRole),
colon = ': ';
if(messageText.indexOf('/action') === 0 || messageText.indexOf('/me') === 0 || messageText.indexOf('/privaction') === 0) {
userClass += ' action';
colon = ' ';
}
if (messageText.indexOf('/privmsg') === 0 || messageText.indexOf('/privmsgto') === 0 || messageText.indexOf('/privaction') === 0) {
rowClass += ' private';
}
var dateTime = this.settings['dateFormat'] ? '<span class="dateTime">'
+ this.formatDate(this.settings['dateFormat'], dateObject) + '</span> ' : '';
return '<div id="'
+ this.getMessageDocumentID(messageID)
+ '" class="'
+ rowClass
+ '">'
+ this.getDeletionLink(messageID, userID, userRole, channelID)
+ dateTime
//start of the code i added
+ '<a href="http://hostname.x/report_chat.php?usernameR='
+ userName
+ '/&useridR='
+ userID
+ '">'
+ '<img src="img/excl.png"></img></a>'
// end of the code i added
+ '<a href="http://www.hostname.x/'
+ userID
+ '" target="_blank"'
+ this.getChatListUserNameTitle(userID, userName, userRole, ip)
+ ' dir="'
+ this.baseDirection
+ '" onclick="ajaxChat.insertText(this.firstChild.nodeValue);">'
+ userName
+ '</a>'
+ colon
+ this.replaceText(messageText)
+ '</div>';
},
If I remove the portion that I added , the page works just fine. When I add it back , I get an Aw Snap error(cache reloaded -> incognito mode )
I'm pretty new with javascript so I can't really tell what I did wrong.
Thank you!
EDIT: THE AW SNAP ERROR comes from the <img> tag for whatever reason.
//Here a simple test
var Obj = (function(){
return{
DOMbufferRowClass : 'DOMbufferRowClass',
getRoleClass : function()
{
return 'roleClass';
},
settings : '',
getMessageDocumentID : function(){
return '123';
},
getDeletionLink : function(messageID, userID, userRole, channelID)
{
return 'DeletiongLink'
},
replaceText : function()
{
},
getChatListMessageString : function(dateObject, userID, userName, userRole, messageID, messageText, channelID, ip) {
var rowClass = this.DOMbufferRowClass,
userClass = this.getRoleClass(userRole),
colon = ': ';
if(messageText.indexOf('/action') === 0 || messageText.indexOf('/me') === 0 || messageText.indexOf('/privaction') === 0) {
userClass += ' action';
colon = ' ';
}
if (messageText.indexOf('/privmsg') === 0 || messageText.indexOf('/privmsgto') === 0 || messageText.indexOf('/privaction') === 0) {
rowClass += ' private';
}
var dateTime = this.settings['dateFormat'] ? '<span class="dateTime">'
+ this.formatDate(this.settings['dateFormat'], dateObject) + '</span> ' : '';
return `<div id="${this.getMessageDocumentID(messageID)}" class="${rowClass}">
${this.getDeletionLink(messageID, userID, userRole, channelID)} ${dateTime}
<a href="http://hostname.x/report_chat.php?usernameR='${userName}/&useridR=${userID}">
<img src="img/excl.png"/></a><a href="http://www.hostname.x/${userID} target="_blank"
this.getChatListUserNameTitle(userID, userName, userRole, ip) dir="{this.baseDirection}
onclick="ajaxChat.insertText(this.firstChild.nodeValue);">${userName}</a>${colon}${this.replaceText(messageText)}</div>`;
}
};
})();
console.log(Obj.getChatListMessageString("05102017", '1234',"admin", '456', 'Test','11', '127.0.0.1'));
I would simplify your code with template literals and avoiding all the concatenation mess.
getChatListMessageString : function(dateObject, userID, userName, userRole, messageID, messageText, channelID, ip) {
var rowClass = this.DOMbufferRowClass,
userClass = this.getRoleClass(userRole),
colon = ': ';
if(messageText.indexOf('/action') === 0 || messageText.indexOf('/me') === 0 || messageText.indexOf('/privaction') === 0) {
userClass += ' action';
colon = ' ';
}
if (messageText.indexOf('/privmsg') === 0 || messageText.indexOf('/privmsgto') === 0 || messageText.indexOf('/privaction') === 0) {
rowClass += ' private';
}
var dateTime = this.settings['dateFormat'] ? '<span class="dateTime">'
+ this.formatDate(this.settings['dateFormat'], dateObject) + '</span> ' : '';
return `<div id="${this.getMessageDocumentID(messageID)}" class="${rowClass}">
${this.getDeletionLink(messageID, userID, userRole, channelID)} ${dateTime}
<a href="http://hostname.x/report_chat.php?usernameR='${userName}/&useridR=${userID}">
<img src="img/excl.png"/></a><a href="http://www.hostname.x/${userID} target="_blank"
this.getChatListUserNameTitle(userID, userName, userRole, ip) dir="{this.baseDirection}
onclick="ajaxChat.insertText(this.firstChild.nodeValue);">${userName}</a>${colon}${this.replaceText(messageText)}</div>`;
}
Ouch! The best approach is not to build your HTML elements in this manner in the first place and use the DOM to construct and inject them into your document.
This makes the code MUCH easier to read and modify and removes the concatenation issue entirely.
Now, if you have errors, you can focus on the values your are assigning to the properties and not the syntax of the HTML.
// Create the div element in memeory
var div = document.createElement("div");
// Configure the attributes of that div
div.id = this.getMessageDocumentID(messageID);
div.classList.add(rowClass);
// Now, begin populating the div
div.innerHTML = this.getDeletionLink(messageID, userID, userRole, channelID) + dateTime;
// A new element belongs inside the div. Repeat the process:
var a1 = document.createElement(a);
a1.href = "http://hostname.x/report_chat.php?usernameR=" + userName + "/&useridR=" + userID;
var img = document.createElement("img");
img.src = "img/excl.png";
// Place the image into the anchor
a1.appendChild(img);
// Place the anchor into the div
div.appendChild(a1);
// Another anchor is now needed
var a2 = document.createElement(a);
a2.href = "http://www.hostname.x/" + userID;
a2.target = "_blank";
// It is unclear what the following line is based on the fact that whatever it returns, you have that
// being inserted where attributes go. It is commented here for that reason.
//this.getChatListUserNameTitle(userID, userName, userRole, ip) + " dir='" + this.baseDirection;
// Set up event handler for the anchor
a2.addEventListener("click", function(){
ajaxChat.insertText(this.firstChild.nodeValue);
});
// Populate the anchor
a2.innerHTML = userName;
// Insert this anchor into the div
div.appendChild(a2);
// Insert the final contents into the div
div.innerHTML += colon + this.replaceText(messageText);
// Return the final construct
return div;

No response from 2nd ajax request

I am getting no response from a 2nd ajax request. I am trying to display an google information window on google map that contains only a single tab when a certain criteria is matched otherwise I want to display two tabs. I thought I could easily implement this with another marker function with tailored behaviour, but I receive no response. Any help on this is always appreciated. Thanks in advance.
// click event handler
google.maps.event.addListener(marker, 'click', function () {
var ecoli_array = [];
var marker = this;
var str = "";
var beach_status; // beach_status flag
// load gif before ajax request completes
infoWindow.setContent('<img src="img/loading.gif" alt="loading data"/>');
infoWindow.open(map, marker);
// override beach data when a beach is closed
beach_status = this.getBeachStatus();
beach_status = beach_status.toLowerCase();
if (beach_status === 'closed') {
str = [
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>' + this.status_description + '</p>'
].join('');
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
} else {
// chained ajax invocations
if ( this.displayOnlyAlgaeResults === false ) {
// Standard Use case
$.when(this.getEcoliData(), this.getAlgaeData()).done(function (data1, data2) {
str += marker.getHeader() + marker.afterGetEcoliData(data1[0].rows);
str += marker.afterGetAlgaeData(data2[0].rows);
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
// render tabs UI
$(".tabs").tabs({ selected: 0 });
}); // end when call
}else{
// Algae Only Use Case
var d = this.getOnlyAlgaeData();
console.log(d);
$.when( this.getOnlyAlgaeData() ).done(function ( rsp ) {
//console.log(rsp);
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp[0].rows );
//str += marker.afterGetOnlyAlgaeData(data2[0].rows);
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
// render tabs UI
$(".tabs").tabs({ selected: 0 });
}); // end when call
} // end inner if else
} // end outer if else
}); // End click event handler
getOnlyAlgaeData: function () { // begin getAlgaeData
var obj;
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=xxxxx&callback=?';
var whereClause = " WHERE 'Beach_ID' = " + this.beach_id;
var query = "SELECT * FROM xxxx "
+ whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
// ecoli request
return $.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp'
});
}, // end getAlgaeData method
// added afterGetOnlyAlgaeData
afterGetOnlyAlgaeData: function (data) {
var algae_rows_str = "";
algae_rows = data;
var algae_rows_str = [
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<table id="algae_table " class="data">',
'<tr>',
'<th>Sample Date</th>',
'<th class="centerText">Blue Green Algae Cells <br/>(cells/ mL) </th>',
'<th>Recreational Water Quality Objective <br/>(100,000 cells/mL)</th>',
'<th class="centerText">Algal Toxin Microcystin <br/> (&#956g/L)</th>',
'<th>Recreational Water Quality Objective <br/> (20 &#956g/L)</th>', // &mu instead of u
'</tr>'
].join('');
//console.log(algae_rows);
if (typeof algae_rows === 'undefined') {
algae_rows_str = [
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>This season, no algal blooms have been reported at this beach.</p>',
'</div>',
'</div>',
'</div>',
'</div>'
].join('');
} else {
for (var i = 0; i < algae_rows.length; i++) {
//console.log(rows[i]);
//algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td class="centerText">' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + checkAlgaeToxinForAdvisory(algae_rows[i][4]) + '</td><td class="centerText">' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + checkBlueGreenAlgaeCellsForAdvisory(algae_rows[i][6]) + '</td></tr>';
algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td class="centerText">' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + checkBlueGreenAlgaeCellsForAdvisory(algae_rows[i][6]) + '</td><td class="centerText">' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + checkAlgaeToxinForAdvisory(algae_rows[i][4]) + '</td></tr>';
}
algae_rows_str += '</table>'
algae_rows_str += '</div></div></div>';
//return algae_rows_str;
} //end if
return algae_rows_str;
}, // end afterGetOnlyAlgaeData
}); // ====================end marker
I essentially copied two identical functions that work, gave them a slightly different name and customized each function to display 1 tab instead of two, but I get no response.
Thoughts?
thanks for the help, it ended up being something simple.
I was incorrectly referencing the response. Ie. I change the following line:
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp[0].rows );
to
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp.rows );
Geez!

How to get next row of HTML table based on some condition using jQuery?

Ok, I am new to JQuery and I have requirement to do some manipulation on table based on rows.
The table consists of rows which belong to 3 different style classes Brand have category and category have products.
var table = $("table tbody");
table.find(".brand").each(function(i) {
var $tdsBrand = $(this).find("td"),
brand = $tdsBrand.eq(0).text(),
atyBrand = $tdsBrand.eq(1).text(),
alyBrand = $tdsBrand.eq(2).text();
console.log('Brand Row ' + (i + 1) + ':\nBrand Name: ' + brand + '\nActual TY: ' + atyBrand + '\nActual LY: ' + alyBrand);
var brandClass = $(this).attr("class");
console.log('brand class : ' + brandClass);
if (this row has next row as category) {
//if(brand.next($( "tr[class='category']" ))) {
//if ("(.band):has(.category)") {
//if ($(this).parents(".category").length == 1) {
table.find(".category").each(function(i) {
var catClass = $(this).attr("class");
console.log('category class : ' + catClass);
var $tdsCategory = $(this).find("td"),
category = $tdsCategory.eq(0).text(),
atyCategory = $tdsCategory.eq(1).text(),
alyCategory = $tdsCategory.eq(2).text();
console.log('Category Row ' + (i + 1) + ':\nCategory Name: ' + category + '\nActual TY: ' + atyCategory + '\nActual LY: ' + alyCategory);
if (This row has next row as product) {
//if(next($( "tr[class='product']" ))) {
//if ("(.category):has(.product)") {
//if ($(this).parents("product").length == 1) {
table.find(".product").each(function(i) {
var proClass = $(this).attr("class");
console.log('product class : ' + proClass);
var $tds = $(this).find("td"),
product = $tds.eq(0).text(),
aty = $tds.eq(1).text(),
aly = $tds.eq(2).text();
console.log('Product Row ' + (i + 1) + ':\nProduct Name: ' + product + '\nActual TY: ' + aty + '\nActual LY: ' + aly);
});
}
});
}
});
What I want to do is, I have to sum up Actual TY values of products and display them on their category. Then sum up Actual TY of categories (which has been calculated from products for different categories) to their brand.
Please refer http://jsfiddle.net/cfhhz0zr/46/ for clear understanding of my requirement and code which I've tried till now.
Thank you.
Just modified a bit your code and it seems that is doing what you are looking for. See also the http://jsfiddle.net/88prg1dt/
I refactored a bit and renamed some variables to make a bit more sense so should be fairly clear now. If you want to calculate the total for a product / category now should be really super simple.
Here is the JS code:
var $table = $("table tbody");
$table.find(".brand").each(function (brandIndex) {
var $brandRow = $(this);
var $tdsBrand = $(this).find("td");
var brandName = $tdsBrand.eq(0).text();
var atyBrand = $tdsBrand.eq(1).text();
var alyBrand = $tdsBrand.eq(2).text();
console.log('Brand Row ' + (brandIndex + 1) + ':\nBrand Name: ' + brandName + '\nActual TY: ' + atyBrand + '\nActual LY: ' + alyBrand);
var $categoryRows = $brandRow.nextUntil('.brand').filter('.category');
$categoryRows.each(function (categoryIndex) {
var $categoryRow = $(this);
var $tdsCategory = $categoryRow.find("td");
var categoryName = $tdsCategory.eq(0).text();
var atyCategory = $tdsCategory.eq(1).text();
var alyCategory = $tdsCategory.eq(2).text();
console.log('Category Row: ' + (categoryIndex + 1) + ':\nCategory Name: ' + categoryName + '\nActual TY: ' + atyCategory + '\nActual LY: ' + alyCategory);
var $productRows = $categoryRow.nextUntil('.brand, .category').filter('.product');
$productRows.each(function (productIndex) {
var $productRow = $(this);
var $tdProducts = $productRow.find("td");
var productName = $tdProducts.eq(0).text();
var atyProduct = $tdProducts.eq(1).text();
var aly = $tdProducts.eq(2).text();
console.log('Product Row ' + (productIndex + 1) + ':\nProduct Name: ' + productName + '\nActual TY: ' + atyProduct + '\nActual LY: ' + aly);
});
});
});
I played a bit with jQuery nextUntil() method as the documentation:
Description: Get all following siblings of each element up to but not
including the element matched by the selector, DOM node, or jQuery
object passed.
Is this answering your question ?

Hiding <p> field in javascript

Here's my code for gathering titles/posts from reddit's api:
$.getJSON("http://www.reddit.com/search.json?q=" + query + "&sort=" + val + "&t=" + time, function (data) {
var i = 0
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
i++
});
});
Basically every post (selftext) is assigned a different paragraph id (post0, post1, post2, etc) for every result that's pulled. I'm also going to create a "hide" button that follows the same id scheme based on my i variable (submit0, submit1, submit2, etc). I want to write a function so that based on which button they click, it will hide the corresponding paragraph. I've tried doing an if statement that's like if("#hide" + i) is clicked, then hide the corresponding paragraph, but obviously that + i doesn't work. How else can I tackle this?
Could you try something like the below?
showhide = $("<a class='hider'>Show/Hide</a>");
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
}
Alternatively:
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var showhide = $("<a class='hider" + i + "'>Show/Hide</a>");
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
});
i++
});

Categories