Find and remove date in jQuery - javascript

I use RSS to get posts from my WordPress website and in its name have date in title and I want to remove the date from its title and use date from rss instead
The Result I want (image) I want to remove date on title (red cross) and use rss date(green underline) instead
The problem is date format in title is not international format
Any idea to make jQuery to detect this date formula and replace(remove) it?
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="http://momentjs.com/downloads/moment-with-langs.min.js"></script>
<script type="text/javascript" src="http://www.sd.ac.th/main/wp-content/rss_fetch/FeedEk.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#divRss').FeedEk({
FeedUrl: 'http://www.sd.ac.th/main/?feed=rss2&cat=121',
//FeedUrl: 'http://www.sd.ac.th/main/?feed=rss2&cat=234',
MaxCount: 10,
ShowPubDate: true,
ShowDesc: false
});
/*setInterval(function(){
$('.itemTitle a').each(function() {
var text = $(this).text();
$(this).text(text
.replace('[', '')
.replace(']', '')
.replace('59', '')
.replace('60', '')
);
});}
, 1);*/
});
function reloadFunction() {
location.reload();
}
</script>
<button onclick="reloadFunction()">R</button>
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="http://www.sd.ac.th/main/wp-content/rss_fetch/rss_style.css">
<div id="divRss"></div>
FeedEk.js (Plugin that I use for fetching my feed)
/*
* FeedEk jQuery RSS/ATOM Feed Plugin v3.0 with YQL API
* http://jquery-plugins.net/FeedEk/FeedEk.html https://github.com/enginkizil/FeedEk
* Author : Engin KIZIL http://www.enginkizil.com
*/
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
DescCharacterLimit: 0,
TitleLinkTarget: "_blank",
DateFormat: "",
DateFormatLang:"en"
}, opt);
var id = $(this).attr("id"), i, s = "", dt;
$("#" + id).empty();
if (def.FeedUrl == undefined) return;
$("#" + id).append('<img src="loader.gif" />');
var YQLstr = 'SELECT channel.item FROM feednormalizer WHERE output="rss_2.0" AND url ="' + def.FeedUrl + '" LIMIT ' + def.MaxCount;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(YQLstr) + "&format=json&diagnostics=false&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
if (!(data.query.results.rss instanceof Array)) {
data.query.results.rss = [data.query.results.rss];
}
$.each(data.query.results.rss, function (e, itm) {
s += '<li><div class="itemTitle"><a href="' + itm.channel.item.link + '" target="' + def.TitleLinkTarget + '" >' + itm.channel.item.title + '</a></div>';
if (def.ShowPubDate){
dt = new Date(itm.channel.item.pubDate);
s += '<div class="itemDate">';
if ($.trim(def.DateFormat).length > 0) {
try {
moment.lang(def.DateFormatLang);
s += moment(dt).format(def.DateFormat);
}
catch (e){s += dt.toLocaleDateString();}
}
else {
s += dt.toLocaleDateString();
}
s += '</div>';
}
if (def.ShowDesc) {
s += '<div class="itemContent">';
if (def.DescCharacterLimit > 0 && itm.channel.item.description.length > def.DescCharacterLimit) {
s += itm.channel.item.description.substring(0, def.DescCharacterLimit) + '...';
}
else {
s += itm.channel.item.description;
}
s += '</div>';
}
});
$("#" + id).append('<ul class="feedEkList">' + s + '</ul>');
}
});
};
})(jQuery);

If it is always and the only thing between brackets ([ and ]) and it's always at the end of the string then use this:
text = text.replace(/(\[.*\])$/, replacementDateString);
Read about Regular Expression.

Related

RSS feed displaying NaN xml jquery

I am coding a simple RSS feed using jquery and a feed from wired. Everything is working great, but for some reason the result is including a NaN after the description. I cannot figure out what it is trying to pull, and since it is not wrapped in any tags, it follows a paragraph as such:
<p></p> NaN </div>
I cannot use css to hide it, and i dont want to limit the description length as some are longer than others and setting an arbitrary character limit may allow it to display anyways on shorter descriptions.
xml feed: http://www.wired.com/category/business/feed/
script:
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
FeedUrl: "http://www.wired.com/category/business/feed/",
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
TitleLinkTarget: "_blank",
}, opt);
var id = $(this).attr("id");
var i;
$("#" + id).empty().append('<img src="loader.gif" />');
$.ajax({
url: "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=" + def.MaxCount + "&output=json&q=" + encodeURIComponent(def.FeedUrl) + "&hl=en&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
var s = "";
$.each(data.responseData.feed.entries, function (e, item) {
s += '<li><div class="itemTitle"><a href="' + item.link + '" target="' + def.TitleLinkTarget + '" >' + item.title + "</a></div>";
if (def.ShowPubDate) {
i = new Date(item.publishedDate);
s += '<div class="itemDate">' + i.toLocaleDateString() + "</div>";
}
if (def.ShowDesc) {
if (def.DescCharacterLimit > 0 && item.content.length > def.DescCharacterLimit) {
var StringStartAfterImage = item.content.indexOf('>',item.content.indexOf('< img')) + 1;
s += '<div class="itemContent">' + item.content.substr(0, def.DescCharacterLimit + StringStartAfterImage) + "..";
}
else {
s += '<div class="itemContent">' + item.content;
}
s += + "</div>";
}
});
$("#" + id).append('<ul class="feedEkList">' + s + "</ul>");
}
});
};
})(jQuery);
$(document).ready(function() {
$('#home-news').FeedEk({
FeedUrl: 'http://www.wired.com/category/business/feed/',
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
});
});
html:
<div class="newsCenter">
<div class="news">
<div id="home-news"> </div>
</div>
</div>
any help is much appreciated! Thank you!
i solved this by removing code after the else statement and closing the div in the else statement, i do not need the data that is not generating so this solution works for me.

Tumblr image remove the limit

I want to get all of the image from my Tumblr blog, (no limit)
even if I change the limit to the large number, by default it became 20 images, I just want to know what is wrong on my codes that I created, please help.. thanks in advance
please check the fiddle above to check the result.
here's my code on jsFiddle
$(document).ready(function(){
var tumblrUrl = 'http://api.tumblr.com/v2/blog/';
var blogUrl = 'blog.campbrandgoods.com';
var apiType = '/posts';
var apiKey = 'VtZPFbyp0dLYfOespTdo6oJyOE0nZx4anBSa46j9OoJO4SBIjg';
var limit = 995;
var postUrl = tumblrUrl + blogUrl + apiType + '?api_key=' + apiKey + '&limit=' + limit;
var tileContainer = $('ul#tiles');
$.ajax({
url: postUrl,
type: 'get',
dataType: 'jsonp',
complete: function(){
},
success: function( strData ){
console.log(strData.response.posts);
var posts = strData.response.posts;
$.each(posts, function (i, v) {
if(typeof v.photos !== 'undefined') {
var n = Math.floor(Math.random() * 6);
var info = $($.parseHTML(v.caption)).text();
tileContainer.append('<li class="item"><div class="tile-img-container"><img src="' + v.photos[0].alt_sizes[2].url + '"></div><div class="tile-info-container"><a class="various fancybox" href="' + v.post_url + '">' + info + '</a></div></li>');
//tileContainer.append('<li class="item"><div class="tile-img-container"><img src="' + v.photos[0].alt_sizes[2].url + '"></div><div class="tile-info-container"><a title="' + info + '" class="various fancybox" href="' + v.photos[0].original_size.url + '">' + info + '</a></div></li>');
}
});
tileContainer.gridalicious({selector: '.item', gutter: 5, animate: true});
$('ul#tiles').on('click', 'li.item', function (e) {
var href = $(this).find('.tile-info-container').find('a').attr('href');
$(this).parents('.item').find('.tile-info-container').find('a').trigger('click');
window.open(href);
//$(this).find('.tile-info-container').find('a').trigger('click');
});
$('ul#tiles').on('click', 'li.item a', function (e) {
e.preventDefault();
});
/*
$("a.fancybox").fancybox({
'type': 'image',
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : true,
'autoScale' : false,
'autoSize' : false,
overlayOpacity: 0.7,
overlayColor: '#000',
onStart :function () {
$('#fancybox-inner').css('width', '97%');
$('#fancybox-inner').css('height', '97%');
},
onComplete: function(){
$('#fancybox-inner').css('width', '97%');
$('#fancybox-inner').css('height', '97%');
}
});
*/
$('.tile-img-container').on('click', function (e) {
$(this).parents('.item').find('.tile-info-container').find('a').trigger('click');
e.preventDefault();
});
}
});
});
#tiles li.item .tile-info-container {
background-color: rgba(0,0,0,0.7);
cursor: pointer;
display: none;
position: absolute;
top: 0;
width: 100%;
height: 100%;
font-size: 11px;
}
<div class="container-fluid">
<div id="page" class="row">
<div class="col-md-12 details">
<ul id="tiles">
</ul>
</div>
</div>
</div>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
On the Tumblr api docs, it is clearly stated that for the request /posts, you're only allowed to have a limit that goes from 1 to 20.
The approach I'd take would be a recursive function that takes an offset argument. (from the following I've removed some code that wasn't working / was commented out)
function GetImages(offset) {
var postUrl = tumblrUrl + blogUrl + apiType + '?api_key=' + apiKey + '&limit=20&offset=' + offset;
$.ajax({
url: postUrl,
type: 'get',
dataType: 'jsonp',
complete: function(){
},
success: function( strData ){
console.log(strData.response.posts);
var posts = strData.response.posts;
$.each(posts, function (i, v) {
if(typeof v.photos !== 'undefined') {
var n = Math.floor(Math.random() * 6);
var info = $($.parseHTML(v.caption)).text();
tileContainer.append('<li class="item"><div class="tile-img-container"><img src="' + v.photos[0].alt_sizes[2].url + '"></div><div class="tile-info-container"><a class="various fancybox" href="' + v.post_url + '">' + info + '</a></div></li>');
//tileContainer.append('<li class="item"><div class="tile-img-container"><img src="' + v.photos[0].alt_sizes[2].url + '"></div><div class="tile-info-container"><a title="' + info + '" class="various fancybox" href="' + v.photos[0].original_size.url + '">' + info + '</a></div></li>');
}
});
$('ul#tiles').on('click', 'li.item', function (e) {
var href = $(this).find('.tile-info-container').find('a').attr('href');
$(this).parents('.item').find('.tile-info-container').find('a').trigger('click');
window.open(href);
//$(this).find('.tile-info-container').find('a').trigger('click');
});
$('ul#tiles').on('click', 'li.item a', function (e) {
e.preventDefault();
});
$('.tile-img-container').on('click', function (e) {
$(this).parents('.item').find('.tile-info-container').find('a').trigger('click');
e.preventDefault();
});
// actual changed part
if (typeof offset === "undefined") {
offset = 0;
}
// (to avoid having to load a hundred pages for each time it was tested, there was also this in the if: `offset < 100 &&`)
if (((offset + 20) < strData.response.total_posts)) {
GetImages(offset + 20);
}
}
});
}
GetImages(0);

Modal not working in external file but works when added as a script before closing body tag

Background
I have a modal that works when added as a script before the closing </body> as
<script>
// Simple modal
jQuery(function ($) {
// Load dialog on click
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal();
return false;
});
});
</script>
or if I have that function as its own .js file and call it that way.
Yes, I did clear my cache and verify in the Inspect Element to see if the script was being called.
Problem
When I put the function in my main javascript file in the app.js it, then the modal does not work.
Current Page
The test page is currently available at http://bruxzir.jgallardo.me/test.aspx
Code
This is the order in which I am calling my scripts from my <head>
<script src="/assets/js/jquery.js"></script>
<script src="/assets/js/mustache.js"></script>
<script src="/assets/js/headroom.min.js"></script>
<script src="/assets/js/jquery.simplemodal.js"></script>
<script src="/assets/js/swipe.js"></script>
<script src="/assets/js/app.js"></script>
<script src="/assets/js/google-analytics.js"></script>
HTML
<div id='basic-modal'>
<h3>Basic Modal Dialog</h3>
<input type='button' name='basic' value='Demo' class='basic'/>
</div>
<!-- modal content -->
<div id="basic-modal-content" class="featured-video">
<img src="http://placehold.it/720x360&text=Image+1">
<img src="http://placehold.it/720x360&text=Image+2">
</div>
app.js
/* Video Modal */
function overlay() {
el = document.getElementById("overlay");
el.style.display = (el.style.display == "block") ? "none" : "block";
}
/* Fixed Header */
$(window).scroll(function(){
if ($(window).scrollTop() >= 180) {
$('nav#page-menu').addClass('fixed-header');
}
else {
$('nav#page-menu').removeClass('fixed-header');
}
});
/* Main functionality for search of labs in the US */
$('#search').keyup(function () {
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('labs.js', function (data) {
console.log(data)
var output = '<ul class="searchresults">';
$.each(data, function (key, val) {
if ((val.abbr.search(myExp) != -1) ||
(val.state.search(myExp) != -1)) {
output += '<li>';
output += '<h5>' + val.name + '</h5>';
output += val.city + ', ' + val.abbr + ' ' + val.country + '<br />';
output += val.phone + '<br />';
output += '<a href="http://' + val.website + '"' + 'target="_blank"' + '>' + val.website + '</a>';
output += '</li>';
}
});
output += '</ul>';
$('#labs-container').html(output);
});
});
/* Passes data from JSON into international lab list */
$(function() {
$.getJSON('labs-international.js', function(data) {
var template = $('#labsCountryList').html();
var html = Mustache.to_html(template, data);
$('#countries').html(html);
});
});
/* Filter for international labs */
$('#lab-country-select').on('change', function (e) {
e.preventDefault();
var cat = $(this).val();
var nam = $(this).val();
$('#countries > div').hide();
$('#countries > div[data-category-type="'+cat+'"][data-category-name="'+nam+'"]').show();
});
/* Main functionality for search of international labs */
$('#search-intl').keyup(function () {
var searchField = $('#search-intl').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('labs-intl.js', function (data) {
console.log(data)
var output = '<ul class="searchresults">';
$.each(data, function (key, val) {
if ((val.country.search(myExp) != -1)) {
output += '<li>';
output += '<h5>' + val.name + '</h5>';
output += val.city + '<br />';
output += val.country + '<br />';
output += val.phone + '<br />';
output += '<a href="http://' + val.website + '"' + 'target="_blank"' + '>' + val.website + '</a>';
output += '</li>';
}
});
output += '</ul>';
$('#labs-container').html(output);
});
});
/* To hide the page navigation */
(function() {
new Headroom(document.querySelector("#page-menu"), {
tolerance: 5,
offset : 180,
classes: {
initial: "slide",
pinned: "slide--reset",
unpinned: "slide--up"
}
}).init();
}());
/* For mobile layout */
$("p").has("img").css({textAlign: "center"});
// Slider for Techincal Information - Polishing Kit
window.mySwipe = new Swipe(document.getElementById('slider'), {
startSlide: 0,
speed: 300,
auto: 600000,
continuous: true,
disableScroll: false,
stopPropagation: false,
callback: function(index, elem) {},
transitionEnd: function(index, elem) {}
});
// Slider for Techincal Information - Seating Instructions
// Add mySwipe2 here and in HTML control
window.mySwipe2 = new Swipe(document.getElementById('slider-2'), {
startSlide: 0,
speed: 300,
auto: 600000,
continuous: true,
disableScroll: false,
stopPropagation: false,
callback: function(index, elem) {},
transitionEnd: function(index, elem) {}
});
// Captions for slider in Technical Information
$(document).ready(function () {
var rm = $(".read-more");
var hi = $('.hide');
rm.click(function (e) {
e.preventDefault();
var now = $(".hide");
now.slideToggle();
hi.not(now).filter(':visible').slideToggle();
});
});
// Simple modal
jQuery(function ($) {
// Load dialog on click
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal();
return false;
});
});
My initial thoughts are that there might be a conflict in the app.js, so
Try this:
// Captions for slider in Technical Information
$(document).ready(function () {
var rm = $(".read-more");
var hi = $('.hide');
rm.click(function (e) {
e.preventDefault();
var now = $(".hide");
now.slideToggle();
hi.not(now).filter(':visible').slideToggle();
});
// Load dialog on click
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal();
return false;
});
});
Mentioned earlier on the comments that I might know the problem, didn't test this but see if this helps. I inserted the code into document.ready() function

How can I open with blank page on this rss javascript nor html?

I have a website which includes this RSS JavaScript. When I click feed, it opens same page, but I don't want to do that. How can I open with blank page? I have my current HTML and JavaScript below.
HTML CODE
<tr>
<td style="background-color: #808285" class="style23" >
<script type="text/javascript">
$(document).ready(function () {
$('#ticker1').rssfeed('http://www.demircelik.com.tr/map.asp').ajaxStop(function () {
$('#ticker1 div.rssBody').vTicker({ showItems: 3 });
});
});
</script>
<div id="ticker1" >
<br />
</div>
</td>
</tr>
JAVASCRIPT CODE
(function ($) {
var current = null;
$.fn.rssfeed = function (url, options) {
// Set pluign defaults
var defaults = {
limit: 10,
header: true,
titletag: 'h4',
date: true,
content: true,
snippet: true,
showerror: true,
errormsg: '',
key: null
};
var options = $.extend(defaults, options);
// Functions
return this.each(function (i, e) {
var $e = $(e);
// Add feed class to user div
if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
// Check for valid url
if (url == null) return false;
// Create Google Feed API address
var api = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;
if (options.limit != null) api += "&num=" + options.limit;
if (options.key != null) api += "&key=" + options.key;
// Send request
$.getJSON(api, function (data) {
// Check for error
if (data.responseStatus == 200) {
// Process the feeds
_callback(e, data.responseData.feed, options);
}
else {
// Handle error if required
if (options.showerror) if (options.errormsg != '') {
var msg = options.errormsg;
}
else {
var msg = data.responseDetails;
};
$(e).html('<div class="rssError"><p>' + msg + '</p></div>');
};
});
});
};
// Callback function to create HTML result
var _callback = function (e, feeds, options) {
if (!feeds) {
return false;
}
var html = '';
var row = 'odd';
// Add header if required
if (options.header) html += '<div class="rssHeader">' + '' + feeds.title + '' + '</div>';
// Add body
html += '<div class="rssBody">' + '<ul>';
// Add feeds
for (var i = 0; i < feeds.entries.length; i++) {
// Get individual feed
var entry = feeds.entries[i];
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
// Add feed row
html += '<li class="rssRow ' + row + '">' + '<' + options.titletag + '>' + entry.title + '</' + options.titletag + '>'
if (options.date) html += '<div>' + pubDate + '</div>'
if (options.content) {
// Use feed snippet if available and optioned
if (options.snippet && entry.contentSnippet != '') {
var content = entry.contentSnippet;
}
else {
var content = entry.content;
}
html += '<p>' + content + '</p>'
}
html += '</li>';
// Alternate row classes
if (row == 'odd') {
row = 'even';
}
else {
row = 'odd';
}
}
html += '</ul>' + '</div>'
$(e).html(html);
};
})(jQuery);
try change this:
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'
to
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'

problem ajax load with autocomplete.?

i created a jquery autocomplete it work true, but loading LOADING... it after removed value by Backspace don't work true. it not hide and Still is show.
how can after removed value by Backspace, hide LOADING... ?
EXAMPLE: Please click on link and see problem
my full code:
$(document).ready(function () {
/// LOADING... ///////////////////////////////////////////////////////////////////////////////////////
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
/// autocomplete /////////////////////////////////////////////////////////////////////////////////////////
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var cl_list = '.' + $(this).closest('div.auto_box').find('ul').attr('class');
var id = '#' + this.id;
var url = $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: dataObj,
cache: false,
success: function (data) {
//alert(url)
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
var id_name = $(cl_list).attr('id');
$(cl_list).show().html('');
if (data == 0) {
$(cl_list).show().html('<p><b>There is no</b></p>');
}
else {
$.each(data, function (a, b) {
//alert(b.name)
$('<p id="' + b.name + '">' + b.name + '</p>').appendTo(cl_list);
});
$(cl_list + ' p').click(function (e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="'+id_name+'[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box ' + specific + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function (e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if ($(specific + ' input').val() == '') {
$(cl_list + " p").hide().remove();
$(cl_list).css('display','none');
$(".list_name").show().html('');
};
$('body').click(function () {
$(cl_list + " p").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
$(cl_list).css('display','none')
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
I recommend you to use jsfiddle next time you post code examples in a link.
Nevermind. The "loading" message keeps there because there's no fallback to empty values on results.
A quick fix could be just by test that there's a value in the input before making any post like if(this.value == ""){
$(cl_list).css('display', 'none');
return false;
}
Here's how it works with it

Categories

Resources