Lee Bok-hyun: Real Estate Boom Breaks Financial Trust
This code snippet contains JavaScript functions for handling news articles, including:
1. jAjax(divId, url, formId, method):
This function is assumed to be a custom AJAX function. it likely sends an asynchronous HTTP request to the specified url. divId: The ID of the HTML element were the response from the server will be placed. if empty, it probably doesn’t update any specific element.
url: The URL to wich the AJAX request is sent.
formId: The ID of the HTML form whose data will be serialized and sent as the request body. If empty, no form data is sent.
method: The HTTP method to use (e.g., “Post”).
2. Document Ready Block:
javascript
$(document).ready(function() {
jAjax('divadditionV2', "/news/NewsView/NewsIssue?Nid=2GRQ1MZ3M4" + "&IsKey=0");
//2024.03.28 dblee 기사 본문 프로그레스바 추가
var content = $('.mainwrap').height();
var contentH = $('.mainwrap').offset().top + $('.articlecon').offset().top + $('.articlecon').height() - $('.seodigitalarea').height();
var progressWid = 0;
$(window).scroll(function() {
var pt = $(window).scrollTop();
progressWid = math.round((pt / contentH) 100);
$('.progress').css("width", progressWid + "%");
});
});
This code executes when the DOM (Document Object Model) is fully loaded.
It first calls jAjax to load content into the divadditionV2 element. The URL includes a news article ID (Nid) and a flag (IsKey).
It then calculates the height of the article content and sets up a scroll event handler.
progress Bar: The scroll event handler calculates the user’s scroll position relative to the article content height and updates the width of an element with the class progress to visually represent the reading progress. This creates a progress bar that fills as the user scrolls down the article.
3. NewsMailSend(Nid, NClass):
This function handles sending a news article via email.
Nid: The news article ID.
NClass: Likely a category or classification of the news article.
It retrieves the article’s title (SnsTitle) from an array called articleslist (which is not defined in the snippet, but assumed to be a global variable). It sets the values of hidden form fields (Nid, NewsMailTitle) and updates the content of an HTML element (NewsMailTitleView) with the article title. It shows a modal popup for sending the email (elements with classes dimed and emailpop). The commented-out code suggests an older implementation of the popup.
4. viewMessageOpen(i) and viewMessageClose():
These functions control the visibility of a message popup (likely for success/error messages related to sending the email).
viewMessageOpen(i): Shows the popup and displays a specific division within it based on the index i.
viewMessageClose(): Hides the popup.
5. SnsShare(Nid, NClass, Kind):
This function handles sharing a news article on social media.
Nid: The news article ID.
NClass: The news article category/classification.
Kind: The social media platform (e.g., “fb” for Facebook, “twt” for Twitter, “kko” for KakaoTalk, ”gplus” for Google+).
It retrieves the article’s title (SnsTitle) from the articleslist array.
It updates hidden form fields (Nid, NClass, Tool) for tracking the share.
It calls jAjax to increment a share counter on the server.
It constructs a URL for sharing the article on the specified social media platform.
Facebook Sharing (fb): This section is more complex and uses the Facebook JavaScript SDK.
It initializes the Facebook SDK with an App ID and version. Vital: You need to replace '502753547182871' with your actual Facebook app ID.
It uses FB.login to prompt the user to log in to Facebook.
If the login is successful, it uses FB.api to scrape the article’s metadata (title, description, image) from the URL. This is important for Facebook to display a rich preview of the shared article.
it opens a Facebook share dialog in a new window.
Other Social media (twt, kko, gplus): For other platforms, it simply constructs the sharing URL and opens it in a new window.
6. SaveNews(Nid, NClass):
This function handles saving a news article (e.g., adding it to a user’s favorites or reading list).
Nid: The news article ID.
NClass: The news article category/classification.
It calls openLoading() (not defined in the snippet, but likely displays a loading indicator).
It updates hidden form fields (Nid, NClass, Tool).
It calls jAjax to save the article on the server. It calls jAjax again to increment a “scrap” counter on the server.7. PrintPop(Nid):
This function opens a new window with a printable version of the news article.
nid: The news article ID.
It opens the /News/NewsView/NewsPrint?Nid= URL in a new window with specific dimensions and scrollbars enabled.
8. PreSaveNews():
This function is incomplete. It doesn’t contain any code within its body. It’s likely intended to perform some action before saving a news article, but the implementation is missing.Key Observations and Potential Improvements:
articleslist: The code relies heavily on a global variable articleslist. This is generally bad practice. It would be better to pass the article data as arguments to the functions or retrieve it from the DOM. Error Handling: The AJAX calls lack error handling. You should add error callbacks to the jAjax function to handle cases where the server returns an error.
Security: Be careful about how you’re constructing URLs, especially when using encodeURIComponent. Make sure you’re not vulnerable to injection attacks.
Facebook App ID: Remember to replace the placeholder Facebook App ID with your actual App ID.
Facebook SDK Version: the Facebook SDK version (v21.0) might be outdated. Check the Facebook Developer documentation for the latest version.
openLoading(): The openLoading() function is not defined. You’ll need to implement this function to display a loading indicator.
Code Duplication: The FB.login block is duplicated in the SnsShare function. This can be refactored into a single function.
Modern JavaScript: the code uses older JavaScript syntax. Consider using const and let for variable declarations and arrow functions for more concise code.
Example of Refactoring the Facebook Sharing Code:
javascript
function shareOnFacebook(Nid, SnsTitle, Link) {
const Title = encodeURIComponent(SnsTitle);
window.fbAsyncInit = function () {
FB.init({
appId: 'YOURFACEBOOKAPPID', // Replace with your actual App ID
cookie: true,
xfbml: true,
version: 'v19.0' // Use the latest version
});
FB.AppEvents.logPageView();
};
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/enUS/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
FB.login(function (response) {
if (response.authResponse) {
const accessToken = response.authResponse.accessToken;
FB.api(
'/me/feed',
'POST',
{
message: SnsTitle,
link: Link,
scrape: true,
accesstoken: accessToken
},
function (response) {
if (!response || response.error) {
console.error('Error posting to Facebook:', response ? response.error : 'Unknown error');
} else {
console.log('Post ID: ' + response.id);
window.open(
'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(Link),
'facebook-share-dialog',
'width=800,height=600'
);
}
}
);
} else {
console.log('user cancelled login or did not fully authorize.');
}
}, {
scope: 'publishactions' // Request publish permissions
});
}
function SnsShare(Nid, NClass, Kind) {
var SnsTitle = articleslist[Nid].SnsTitle;
$('#Tool').val(Kind);
$("#NewsCountForm input[id=Nid]").val(Nid);
$("#NewsCountForm input[id=NClass]").val(NClass);
jAjax("", "/News/NewsView/SnsCount", "NewsCountForm", "Post");
var domain = "";
var Link = encodeURIComponent(domain + "/NewsView/" + Nid + "?outlink=" + Kind);
if (Kind == "fb") {
shareOnFacebook(Nid, SnsTitle, domain + "/NewsView/" + Nid + "?OutLink=" + Kind);
return;
} else if (Kind == "twt") {
Url = "" + Link + "&text=" + encodeURIComponent(snstitle);
} else if (Kind == "kko") {
Url = "" + Link;
} else if (Kind == "gplus") {
Url = "" + Link;
}
window.open(Url, "SnsSharePop", "width=500,height=450");
}
Key changes in the refactored Facebook code:
shareOnFacebook function: Encapsulates the Facebook sharing logic.
Error Handling: Includes error handling in the FB.api callback. publishactions scope: Requests the publishactions permission, which is required to post to the user’s timeline. Facebook’s permission requirements can change, so always consult their documentation. simplified Sharing URL: uses the standard Facebook Sharer URL as a fallback.
Removed Redundant Code: The duplicated FB.login block is removed.
Modern Syntax: Uses const for variable declarations.
Remember to adapt this code to your specific needs and test it thoroughly. Always refer to the official documentation for the Facebook JavaScript SDK and other social media platforms for the moast up-to-date facts.
Understanding and Improving JavaScript Code for News Article Handling
This document analyzes JavaScript code snippets designed to manage news articles, focusing on their functionalities, potential improvements, and best practices. The code handles tasks such as sharing articles on social media, saving articles, printing articles, and tracking various user interactions.
1. Core AJAX Function (jAjax)
The jAjax(divId, url, formId, method) function is basic to the code’s operation. It’s designed to manage asynchronous requests to a server. This function is likely a custom implementation for sending AJAX requests.
Purpose: To communicate with the server without fully reloading the page.
Parameters:
divId: the HTML element ID intended to display the server response. when empty, the response is not directed to a specific element.
url: The web address the request is sent to.
formId: The ID of the HTML form containing request data. If empty, then no form data is sent to the server.
method: The HTTP method used for the request (e.g., “POST”).
2.Document Ready Block
The $(document).ready(function() { ... }); block ensures that the JavaScript code runs after the HTML document has fully loaded. This prevents errors that might occur if the code tries to manipulate elements that aren’t yet present in the DOM.
Functionality: Executes AJAX requests to fetch related news or details for a specific news item.
3. SnsShare(Nid, NClass, Kind): Sharing News on Social Media
This function handles sharing the news article on various social media platforms. The function calls jAjax and sets hidden form fields, retrieves the article title (SnsTitle), constructs social media-specific sharing URLs, and facilitates sharing on the designated platform. The Facebook implementation is more complex and uses the Facebook JavaScript SDK.
Nid: The ID of the news article.
NClass: The category of the news article.
Kind: The social media platform (e.g., "fb", "twt", "kko").
Facebook Sharing
Initializes the Facebook SDK with an App ID and version.
Uses FB.login to prompt the user to log in to Facebook.
If the login is accomplished, FB.api is used to scrape article metadata (title,description,images).
Opens a share dialog in a new window.
Other Social Media (twt, kko, gplus)
Constructs sharing URLs.
opens a new window with these URLs.
4. SaveNews(Nid, NClass): Saving News Articles
The function saves a news article (e.g., adding it to a user’s favorites or reading list). It calls jAjax functions for saving the article and increments a “scrap” counter.
Nid: The article's ID.
NClass: The article category.
5. printpop(Nid): Printing News Articles
This function opens a new window for printing a formatted view of the article.
nid: The ID of the article.
Opens a new window at a print-specific URL.
6. PreSaveNews(): Readiness before saving
This function is incomplete. It is indeed not intended to contain any code. It is likely intended to perform some action before saving a news article.
Key Areas for Improvement
articleslist Dependency: The code relies on a global variable named articleslist. It’s better to pass article data as function arguments or retrieve the data from the DOM, improving code organization.
Error Handling: Implement AJAX error handling with error callbacks in jAjax to manage server-side failures.
Security: Carefully construct URLs, especially when using encodeURIComponent, to prevent injection attacks.
Facebook App ID: Replace the placeholder Facebook App ID.
Facebook SDK Version: Update the Facebook SDK version to the latest (check Facebook Developer documentation) for access to the latest features and security updates
openLoading() Implementation: Implement this function to display loading indicators during AJAX calls.
Code Duplication: Refactor duplicate blocks of code, for instance, within the Facebook sharing function, to make the code more maintainable and efficient.
Modern JavaScript: Utilize const and let for variable declarations and arrow functions for more concise and readable code.
Refactored Facebook sharing Code Example
This example shows how to refactor the Facebook sharing code, improving it’s structure and readability:
javascript
function shareOnFacebook(Nid, SnsTitle, Link) {
const Title = encodeURIComponent(SnsTitle);
window.fbAsyncInit = function () {
FB.init({
appId: 'YOURFACEBOOKAPPID', // Replace with your actual App ID
cookie: true,
xfbml: true,
version: 'v19.0' // Use the latest version
});
FB.AppEvents.logPageView();
};
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/enUS/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
FB.login(function (response) {
if (response.authResponse) {
const accessToken = response.authResponse.accessToken;
FB.api(
'/me/feed',
'POST',
{
message: SnsTitle,
link: Link,
scrape: true,
accesstoken: accessToken
},
function (response) {
if (!response || response.error) {
console.error('Error posting to facebook:', response ? response.error : 'Unknown error');
} else {
console.log('Post ID: ' + response.id);
window.open(
'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(Link),
'facebook-share-dialog',
'width=800,height=600'
);
}
}
);
} else {
console.log('user cancelled login or did not fully authorize.');
}
}, {
scope: 'publishactions' // Request publish permissions
});
}
function SnsShare(Nid, NClass, Kind) {
var SnsTitle = articleslist[Nid].SnsTitle;
$('#Tool').val(Kind);
$("#NewsCountForm input[id=Nid]").val(Nid);
$("#NewsCountForm input[id=NClass]").val(NClass);
jAjax("", "/News/newsview/SnsCount", "NewsCountForm", "Post");
var domain = "";
var Link = encodeURIComponent(domain + "/NewsView/" + nid + "?outlink=" + Kind);
if (Kind == "fb") {
shareOnFacebook(Nid, SnsTitle, domain + "/NewsView/" + Nid + "?OutLink=" + Kind);
return;
} else if (Kind == "twt") {
Url = "" + Link + "&text=" + encodeURIComponent(snstitle);
} else if (Kind == "kko") {
Url = "" + Link;
} else if (Kind == "gplus") {
Url = "" + Link;
}
window.open(Url, "SnsSharePop", "width=500,height=450");
}
Key improvements in the refactored code:
shareOnFacebook Function: Encapsulates Facebook sharing logic.
Error Handling: Includes error handling.
publish_actions Scope: Requests necessary permissions for posting to the user’s timeline.
Simplified Sharing URL: Uses the standard facebook Sharer URL as a fallback.
Removed Redundant Code
Modern Syntax
Conclusion
By addressing these improvements, the JavaScript code can become more robust, maintainable, and user-amiable, improving the overall quality and user experience of the news article handling functionality.
