Using jQuery on dynamically loaded element - javascript

I am using the following code to retrieve the number of likes from the Facebook Graph API, and this works perfectly. What I am having trouble doing is using jQuery .css to alter the color of the last character in the returned value.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/krewella?callback=?";
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url,function(json){
var html = "<ul><li>" + json.likes + "</li><li>" + json.about + "</li></ul>";
//A little animation once fetched
$('.facebookfeed').animate({opacity:0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity:1}, 500);
});
});
</script>
</head>
<body>
<div id="wrapper"><!--wrapper open-->
<div class="facebookfeed">
<h2>Loading...</h2>
</div>
</div><!--wrapper closed-->
</body>

How about something like:
json.likes = json.likes.toString().slice(0,-2) + "<span class='red'>" + json.likes.toString().substr(-1) + "</span>"
var html = "<ul><li>" + json.likes + "</li><li>" + json.about + "</li></ul>";
With the trivial css:
.red{
color:#ff0000;
}

Related

Thymeleaf var as value of attribute

$("#comparison-qty").html('<div id="comparison-qty"><a href="'+
[[${url_compare_view}]] +'">' + error.transport + '</a></div>');
Hello, I have this code. I want [[${url_compare_view}]] this thymeleaf var to be value of attribute href, but it isn't work. Where wrong?
First you have to store your variable on inline script, in order to access its data later, because thymeleaf only works in html page not on js files. Try this.
<script th:inline="javascript">
/*<![CDATA[*/
var urlCompareView = /*[[${url_compare_view}]]*/ 'url_compare_view';
/*]]>*/
</script>
Then you can use ir on your javascripts.
$("#comparison-qty").html('<div id="comparison-qty">' + error.transport + '</div>');
Hope it helps you.
Edit
If you want do it all inlinie. try this.
<script th:inline="javascript">
/*<![CDATA[*/
var urlCompareView = /*[[${url_compare_view}]]*/ 'url_compare_view';
$("#comparison-qty").html('<div id="comparison-qty">' + error.transport + '</div>');
/*]]>*/
</script>

How to call method in Controller from View on a javascript event in RoR?

I am new to RoR. I have a view file which uses javascript. Upon clinking a button, I want to call a method in Controller. How do I do that.
JS code: (folder_view.js)
function iterate(data){
var folder_names = "";
$.each(data.Folder, function(key, val) {
folder_names = folder_names + "<ul> <li id= '" + val.folder_name + "'>
<a class='a' href='' onclick='updateDiv(val.folder_name)'>" + val.folder_name +
"</a></li></ul>";
});
var divid = "folder";
var view_var2 = jQuery("<div class='scrollbar ' id='divscroll' > <div class='content ' id = " + divid + "> <ul> <li> Folder " + folder_names + "</li></ul></div></div>");
$('#folder_view').html(view_var2);
tree_view(divid);
}
function tree_view(divid){
$("#" + divid).jstree();
$("#" + divid).on("changed.jstree", function (e, data) {
console.log(data.selected);
});
$('button').on('click', function () {
$("#" + divid).jstree(true).select_node('child_node_1');
$("#" + divid).jstree('select_node', 'child_node_1');
$.jstree.reference("#" + divid).select_node('child_node_1');
});
}
Here, I am calling the UpdateDiv method upon clinking on folder. This method is available in view file which is as follows:
Folder_view.html.erb:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<script type="text/javascript" src="/assets/folder_view.js"></script>
<script type="text/javascript" src="/assets/jstree.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON('/assets/temp.json', function(data) {
iterate(data);
});
});
function updateDiv(data){
//Call a function to controller
}
</script>
<body class="bonita-body" ieonload="">
<div id="bonita_process_label" class="bonita_process_label"><div class="gwt-HTML">Console</div></div>
<div id="bonita-banneralthaut"></div>
<div id="bonita-banneraltbas"></div>
<div style='margin-top: 40px;'> <div id='folder_view'></div>
</body>
The method updateDiv is being called upon clicking a folder_name. I want fetch some folder-specific meta-data from controller for the same. How do I call any method from view to controller upon clinking?
Any references??
You need to make an AJAX call using either native XHR:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
OR by using jQuery AJAX:
https://api.jquery.com/jQuery.ajax/

Read json until "more" comment

I want to pull from a tumblr blog and display it on another webpage using javascript.
I'm using the $TUMBLR_BLOG/api/read/json feed which provides a variable filled with the information from the blog post.
I want to print everything up to the "<!-- more -->" set of characters in the 'regular-body' section, ie. I don't want to print everything in the 'regular-body' just up to that more section.
Any thoughts on how to do that?
Eg. API read: http://blog.intercut.yegfilm.ca/api/read/json
Eg. Basic code I'm using:
<script type="text/javascript" src="http://blog.intercut.yegfilm.ca/api/read/json"></script>
<script type="text/javascript">
// The variable "tumblr_api_read" is now set.
document.write(
'<h3> ' + tumblr_api_read.posts[0]['regular-title'] + '</h3>' +
tumblr_api_read.posts[0]['regular-body']);
</script>
<script type="text/javascript">
// The variable "tumblr_api_read" is now set.
var url = tumblr_api_read.posts[0]['url'];
var title = tumblr_api_read.posts[0]['regular-title'];
var body = tumblr_api_read.posts[0]['regular-body'];
body = body.substring(0,body.indexOf("<!-- more -->"));
document.write('<h3> ' + title + '</h3>' + body);
</script>
Simple as that :)
Something like responseData.split("<!-- more -->")[0] ?
Get the index of the <!-- more --> and print the substring upto that index.
sampleString = "Foo <!-- more --> Bar";
moreIndex = sampleString.indexOf("<!-- more -->");
if (moreIndex > 0) {
console.log(sampleString.substring(0, moreIndex));
}
JSFiddle
Use the javascript SubString() method:
Example:
var mystring = 'Hello World <!-- more -->';
alert(mystring.substring(0,mystring.indexOf("<!-- more -->")));
jsFiddle: http://jsfiddle.net/8CXd8/
Documentation: http://www.w3schools.com/jsref/jsref_substring.asp

perform a fetch query on html popup

I have created a html web resource that I am showing when a ribbon button is clicked. On this popup I have a drop down list that I want to populate with a list of records that I have obtained using a fetchXml query.
My problem is that I have tried a few different ways to execute the query but it always comes back with errors. I'm guessing that the popup wont have the same range of functions that the parent form will have and so I will need to do something different to execute the query.
Currently I have it so that I have loaded an external script containing the functions needed to perform the fetch, but the code cannot see the CRM function of _HtmlEncode, and therefore fails.
Is there any way that I can get the popup to see the CRM functions? Or is there an alternate way of doing this?
EDIT: Some sample code
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:asp>
<head>
<title>Re-Assign</title>
<script type=text/javascript src="ClientGlobalContext.js.aspx"></script>
<script type=text/javascript src="http://crm/DEVCRM/WebResources:ts_/scripts/fetch_global.js"></script>
<script type=text/javascript>
function OnLoad_GetAreasAndConsultants() {
var fetchXml = '<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0"><entity name="ts_solution_area"><attribute name="ts_solution_areaid"/><attribute name="ts_descriptor"/><attribute name="createdon"/> <order descending="false" attribute="ts_descriptor"/><filter type="and"><condition attribute="statecode" value="0" operator="eq"/></filter></entity></fetch>';
var fetchedRecords = FetchRecordsToolKit.Fetch(fetchXml);
if (fetchedRecords !== null) {
var areaList = document.getElementById("ddl_solution_area")
for (var i=0; i<fetchedRecords.length;i++) {
var name = fetchedRecords[i].getValue("ts_descriptor");
areaList.options[select.options.length] = new Option(name, i);
}
}
}
</script>
Thanks
I built something specifically for executing fetch within an HTML web resource.
https://github.com/paul-way/JCL/blob/master/jcl.js
Here's an example of using it:
var processProjectInfo = function (data) {
if (data.length > 0) {
// Set Project Header Information
$('#ProjectTitle').html(data[0].attributes.new_name.value);
$('#CompanyName').html(data[0].attributes.new_accountid.name);
}
};
var loadProjectInfo = function (guid) {
var fetchXML = " " +
"<fetch mapping='logical' count='10'>" +
" <entity name='new_project'>" +
" <all-attributes/>" +
" <filter>" +
" <condition attribute='new_projectid' operator='eq' value='" + guid + "' />" +
" </filter>" +
" </entity>" +
"</fetch>";
JCL.Fetch(fetchXML, processProjectInfo);
};

jquery .find and append img tag

I am trying to load pictures name from a xml object and append to div. I am getting confuse with append typing layout, not able to find where im doing typing mistake.
This is working
$("#nn").append("<img id='theImg' src='/pic/jas/pic1.jpg'/>");
This not working
$("#nn").append("<img id='theImg' src='/pic/jas/'" + customer.find("pic_name") + "/>");
My jquery script part is
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var pic_infoVar = xml.find("pic_info");
pic_infoVar.each(function () {
var customer = $(this);
$("#picDiv").append("<img id='theImg' src='/pic/jas/'" + customer.find("pic_name") + "/>");
});
$("#loader").hide();
}
Html Div tag
<div id="picDiv">
LoadPic
</div>
Provded that pic_name is infact an element in an XML data structure (ex: <pic_name>pic1.jpg</pic_name>), the code that will do what you want is:
$("#nn").append("<img id='theImg' src='/pic/jas/" + customer.find("pic_name").text() + "'/>");
This is how i used to do
document.getElementById('nn').innerHTML +='<img src="'+customer.find(\"pic_name\")+'"/>';

Categories