auto refresh json without reload - javascript

i am trying to make an auto refresh json which is reloading for changes every 5 seconds. It loads perfectly first time on load but my setinterval is not working correctly. It goes of every 5 seconds but it doesnt update my menu even though changes has been made? .
Here is what i got so far:
$(document).ready(function(load) {
var dmJSON = "example.com";
$.getJSON( dmJSON, function(data) {
setInterval(function () {
$(news).html("");
$.getJSON();
}, 5000);
var html = '';
// loop through all the news items, and append the
// title and published date to the html variable.
for(var i = 0; i < data.feed.data.length; i++){
html += '<div style="width: 600;direction: rtl;background-color: white;padding: 12px 12px 0;border: 1px solid;border-color: #e5e6e9 #dfe0e4 #d0d1d5;border-radius: 4px;margin-bottom: 20px;color: black;">';
html += '<span style="/* text-align: left; */direction: rtl;position: absolute;left: 250px;"> ' + data.feed.data[i].created_time + ' </span><span><img alt="" src="http://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Network-Globe-Disconnected-icon.png" style="background-size:auto;background-repeat: no-repeat;display: inline-block;height: 20px;width: 20px;position: absolute;left: 490px;padding-top: 9px;" /></span>' ;
html += '<br>' ;
html += data.feed.data[i].message ;
html += '<p><img alt="" src=' + data.feed.data[i].picture + ' /></p>';
html += '</div>';
}
// append all the html variable to the ticker div.
$("#news").append(html);
});
});
i use this code but when refresh he give my empty page
setInterval(function () {
$(news).html("");
$.getJSON();
}, 5000);

Try this:
$(document).ready(function(load) {
var dmJSON = "https://";
function fetch() {
$.getJSON( dmJSON + (+new Date()), function(data) {
$("#news").html('');
var html = '';
// loop through all the news items, and append the
// title and published date to the html variable.
for(var i = 0; i < data.feed.data.length; i++){
html += '<div style="width: 600;direction: rtl;background-color: white;padding: 12px 12px 0;border: 1px solid;border-color: #e5e6e9 #dfe0e4 #d0d1d5;border-radius: 4px;margin-bottom: 20px;color: black;">';
html += '<span style="/* text-align: left; */direction: rtl;position: absolute;left: 250px;"> ' + data.feed.data[i].created_time + ' </span><span><img alt="" src="http://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Network-Globe-Disconnected-icon.png" style="background-size:auto;background-repeat: no-repeat;display: inline-block;height: 20px;width: 20px;position: absolute;left: 490px;padding-top: 9px;" /></span>' ;
html += '<br>' ;
html += data.feed.data[i].message ;
html += '<p><img alt="" src=' + data.feed.data[i].picture + ' /></p>';
html += '</div>';
}
// append all the html variable to the ticker div.
$("#news").append(html);
});
}
setInterval(fetch, 5000);// call fetch every 5 seconds
fetch(); // call fetch first time
});

Related

Unable to display JavaScript / jQuery div tag without dependency on another tag

I'm using JavaScript with jQuery to display my RSS Medium feed when there is a <div id="medium-feed"... on the page.
When the JSON data is pulled, I display the data using HTML, some CSS, and the bootstrap library with day.js (to format the date). So far it worked as expected (see code snippets at the bottom).
I also want to display a more compact version of the feed to my footer that shows the title and published date. So I copied down my original code and have JavaScript look for a <div id="medium-feed-footer"... to display the other version of the feed so it can look like this:
This only works if I show both of my div elements on the same page, like my blog page:
<div id="medium-feed" username="factmaven" read-more="Read More"></div>
<div id="medium-feed-feed" username="factmaven"></div>
But if I visit any other page that only shows the footer version of my feed, it's empty, as seen on my homepage. When you test out my code snippet, just add the -footer part in the ID on its own and it won't show up. It looks like there is a dependency to show both div tags in order for it to work properly.
How can I have my footer version show up independently? I tried various ways such as breaking this code into two separate files and trying an if/then statement, but the result is always the same.
$(document).ready(function() {
// Get option values
var divID = 'medium-feed';
var mediumUsername = document.getElementById(divID).getAttribute('username');
var readMore = document.getElementById(divID).getAttribute('read-more');
/* Medium Feed */
document.getElementById(divID).innerHTML =
($.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/' + mediumUsername,
function(json) {
$('#' + divID).html('');
// For loop each Medium post in HTML structure
for (var i in json.items) {
// Define custom value with regex and replace
var thumbnail = json.items[i].thumbnail.replace(/max\/(.+?)\//g.exec(json.items[i].thumbnail)[1], $('#' + divID).width());
var subtitle = /<p class="medium-feed-snippet">(.+?)<\/p>/g.exec(json.items[i].description)[1];
var pubDate = dayjs(json.items[i].pubDate).format('MMM D, YYYY');
var categories = json.items[i].categories.join(', #');
// HTML post structure
$('#' + divID).append(
'<div class="blog-post col-lg-4 col-md-6 col-sm-12">' +
'<div class="blog-post-date">' + pubDate + '</div>' +
'' +
'<a href="' + json.items[i].link + '" target="_blank" ' + 'title="' + json.items[i].title + '">' +
'<h3>' + json.items[i].title + '</h3>' +
'</a>' +
'<small>by ' + json.items[i].author + '</small>' +
'<hr>' +
'<p>' + subtitle + '.</p>' +
'<small>#' + categories + '</small>' +
'<p>' + readMore + ' <i class="fas fa-long-arrow-alt-right"></i></p>' +
'</div>'
);
}
}));
/* Footer Medium Feed */
document.getElementById(divID + '-footer').innerHTML =
($.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/' + mediumUsername,
function(json) {
$('#' + divID + '-footer').html('');
// For loop each Medium post in HTML structure
for (var i in json.items.slice(0, 5)) {
var pubDate = dayjs(json.items[i].pubDate).format('MMM D, YYYY');
// HTML post structure
$('#' + divID + '-footer').append(
'<a href="' + json.items[i].link + '" target="_blank" ' + 'title="' + json.items[i].title + '">' +
'<h4>' + pubDate + '</h4>' +
'<h5>' + json.items[i].title + '</h5>' +
'</a>'
);
}
}));
});
.blog-post-image {
width: 100%;
background-repeat: no-repeat;
background-position: 50%;
background-size: cover;
overflow: auto;
display: block;
}
.blog-post-image:after {
content: "";
display: block;
position: relative;
margin-top: 60%;
width: 100%;
z-index: 1;
}
.blog-post-date {
position: absolute;
background-color: #ffffff;
padding: 5px;
color: #000000;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.9.6/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-offset-1 col-md-10 col-sm-12">
<div class="section-title">
<h3>Latest Blog Posts</h3>
</div>
<div id="medium-feed" username="factmaven" read-more="Read More"></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
On other pages, Javascript doesn't find an element with id = "medium-feed" so it returns an error. First, check if the element exists.
$(document).ready(function() {
// Get option values
var divID = 'medium-feed';
var mediumUsername = document.getElementById(divID).getAttribute('username');
var readMore = document.getElementById(divID).getAttribute('read-more');
/* Medium Feed */
var divContainer = document.getElementById(divID);
if (divContainer) {//check if element exists
divContainer.innerHTML = ($.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/' + mediumUsername,
function(json) {
//rest of your code
}))
}
})

jQuery getting height of div returns 0

i have a jquery html object:
var $header = $('<div id="print-header" class="print-header" style="width: ' + this.previewWidth + 'px; min-height: 190px;"></div>');
When I output it with console.log($header); I can see the object.
Now after that comes a for loop that appends elements, with a float: left on them to the $header object
for(var i = 0; i < $form.length; i++){
var $widget = $form[i];
var wHtml = '<div class="element" style="width: ' + $widget.size_x*10 + '%; height: ' + $widget.size_y*10 + '%; float: left;">';
switch($widget.widget_name){
case "textFieldWidget":
wHtml += '<div style="border-bottom: 2px dotted; width: 100%; height: 30px; margin: 5px;"><span style="position: relative; font-size: 11px; font-style: italic; color: #999; top: 16; left: 10;">' + $widget.name + '</span></div>';
break;
...
case "imageWidget":
wHtml += '<div style="margin: 5px;"><img src="' + $widget.options[0].value + '" style="width: 100%; height: 100%;"></div>';
break;
}
wHtml += '</div>';
if($widget.section == 0){
$header.append(wHtml);
}
...
}
During the loop, when the element has been appended, I append a clearfix to the $header
$header.append('<div class="clear" style="clear: both;"></div>');
At this point I need to calculate the $header height to do some further processing and this is the part where I'm stuck. No matter whether I use .height(), .outerHeight(), .innerHeight() or .prop("scrollHeight"), the height is always returned 0.
console.log($header); // returns the $header object
console.log("Normal: " + $header.height()); // returns 0
console.log("Outer: " + $header.outerHeight()); // returns 0
console.log("Inner: " + $header.innerHeight()); // returns 0
console.log("Scroll: " + $header.prop("scrollHeight")); // returns 0
I have tried using $(window).load(), that didn't work. The div is visible (display: block;). I also tried adding overflow: hidden;, that didn't work aswell
After appending elements to DOM the Browser needs to render. With a short wait you should be able to get the height.
First make sure you append the header to the DOM otherwise it's not rendered and hence never gets a height.
document.body.appendChild($header);
$header.append('<div class="clear" style="clear: both;"></div>');
console.log($header); // returns the $header object
setTimeout(function(){
console.log("Normal: " + $header.height());
console.log("Outer: " + $header.outerHeight());
console.log("Inner: " + $header.innerHeight());
console.log("Scroll: " + $header.prop("scrollHeight"));
}, 100);

Adding dynamic styles with conditions to the dom elements

I am generating divs dynamically but What I want is to add a anchor tag that shows a trash image for deleting that particular message on hover of a particular div. I have written a :hover on class to add background and that is working fine but I want to add an anchor tag also . Here is my code::
Style
<style>
.mail:hover {
background-color: #cde6f7;
/*background-image: url("/Content/images/Trash.png");*/
}
.mail {
float: left;
width: 100%;
border-bottom: solid 1px #ccc;
padding-bottom: 10px;
margin-top: 3px;
cursor: pointer;
}
</style>
Here I am creating the dynamic div's and I want to add background color and an trash image image to everydiv I hover
<script>
success: function (data) {
if (data.MessageData != null) {
var DataDiv = "";
for (var iRow = 0; iRow < data.MessageData.length; iRow++) {
var RowData = data.MessageData[iRow];
var date = new Date(parseInt(RowData.Sent_Date.substr(6)));
var style = '';
if (RowData.IsReceiver_Received == false) {
style = 'color:#0460C7' + '!important ';
}
DataDiv += "<div class='mail' id='" + RowData.pkMessageId + "' onclick=ShowMessage('" + RowData.pkMessageId + "')>";
DataDiv += "<h3 style=" + style + ">" + RowData.Subject + "</h3>";
//<label class='label' style='color:red ! important;'> hi hi hi </label>
DataDiv += "<label style=" + style + "class='clsLbl'> From:" + RowData.Message_From + "</label>";
DataDiv += "<label style=" + style + "class='clsLb2'>" + date.toDateString() + "</label></div>";
}
$("#hdnSearchType").val(1);
$("#hdnUserType").val(1);
}
$("#MessageStore").html('');
$("#MessageStore").html(DataDiv);
},
</script>
$(".mail").live('hover', function(e){
$("#"+this.id).append("<a>addd</a>");
});
If I understand your question properly, you would need to do this:
While dynamically creating the <div>'s HTML, also add this inside the div:
DataDiv += "<a href='its-url' class='trash'></a>";
This will add an anchor inside your dynamic elements.
Since you want to keep this hidden and it will be only visible when you hover over the "mail" div,
.trash { display: none; }
.mail:hover .trash { display: block; }
Will work for you.
You can then use background-image or <img src=""> to show the trash icon inside this anchor element.

How to make a scrollable div with dynamic content

I am trying to add an image into my div inside bottom to top when I click the add button. Now it is working, but my problem was the div does not scroll. What I am doing wrong?
JSFiddle link
HTML
<button id="add_content">Add</button>
<div class="image_panel"></div>
CSS
.image_panel {
width:100%;
height:300px;
border:1px solid red;
overflow-y:scroll;
}
#add_content{
float:left;
}
JavaScript
$(document).ready(function() {
var smallimg_count=0;
var bottom=0;
$("#add_content").click(function() {
smallimg_count++;
bottom=bottom+20;
var insert_html_small = '<div id="imageGrid_' + smallimg_count + '" class="imageGrid_small" >
<img class="resize1" id="resize_' + smallimg_count + '" src="http://webbies.dk/assets/templates/SudoSlider/images/toolbox_designer.png" style="bottom:' + bottom + 'px;" />
</div>';
$(insert_html_small).appendTo(".image_panel");
});
});
One issue that I see is that the image you are adding has an absolute position inline style (from your JSFiddle)
e.g.
style="bottom:' + bottom + 'px; position: absolute;'
Therefore it's in a different stacking context than the div
Removing it seems to make it work: http://jsfiddle.net/4Ftev/12/
e.g.
$(document).ready(function () {
var smallimg_count = 0;
var bottom = 0;
$("#add_content").click(function () {
smallimg_count++;
bottom = bottom + 20;
var insert_html_small = '<div id="imageGrid_' + smallimg_count + '" class="imageGrid_small" ><img class="resize1" id="resize_' + smallimg_count + '" src="http://webbies.dk/assets/templates/SudoSlider/images/toolbox_designer.png" /></div>';
$(insert_html_small).appendTo(".image_panel");
});
});
If you want to add it bottom up, then you can use prependTo, see this JSFiddle
http://jsfiddle.net/4Ftev/15/
$(document).ready(function () {
var smallimg_count = 0;
var bottom = 0;
$("#add_content").click(function () {
smallimg_count++;
bottom = bottom + 20;
var insert_html_small = '<div id="imageGrid_' + smallimg_count + '" class="imageGrid_small" >' + smallimg_count + '<img class="resize1" id="resize_' + smallimg_count + '" src="http://webbies.dk/assets/templates/SudoSlider/images/toolbox_designer.png" /></div>';
$(insert_html_small).prependTo(".image_panel");
});
});
You are using an absolute positioned image, inside a div which is not relative positioned.
First of all, add position:relative; to the .image_panel class style
What you will notice now, is that the image is positioned relative to the div.
If you want to test the scrollbar, i would recommend you to use a margin instead of the absolute positioning on your image.
Like, margin-top:900px;
Css
.image_panel
{
width:100%;
height:300px;
border:1px solid red;
overflow-y:scroll;
position:relative;
}
#add_content{
float:left;
}
Javascript
$(document).ready(function(){
var smallimg_count=0;
var bottom=500;
$("#add_content").click(function(){
smallimg_count++;
bottom=bottom+20;
var insert_html_small = '<div id="imageGrid_' + smallimg_count + '" class="imageGrid_small" ><img class="resize1" id="resize_' + smallimg_count + '" src="http://webbies.dk/assets/templates/SudoSlider/images/toolbox_designer.png" style="margin-top:' + bottom + 'px;" /></div>';
$(insert_html_small).appendTo(".image_panel");
});
});
http://jsfiddle.net/3gzaW/
Best regards.
Jonas
Your images:
<img class="resize1" id="resize_3" src="http://webbies.dk/assets/templates/SudoSlider/images/toolbox_designer.png" style="bottom:60px; position: absolute;;">
Take away the position:absolute; (make it relative, or remove it entirely)

JQuery append elements are going out of parent div width?

I have a html div which is styled using bootstrap class span9.
<div class="span9">
<div id = "selectedtags" class="well">
</div>
<button class="btn" type="button" id="delegatecontent">Create report</button>
</div>
What i am trying to achieve is, write a jquery click event on following li tags (20+ li tags in actual ) and append the newly created element inside the #selectedtags div.
<li class="dbcol">Location_Id</li>
<li class="dbcol">Location_Name</li>
<li class="dbcol">Location_EN</li>
Following is my javascript (Jquery) code to append span tags inside the #selectedtags div.
$(document).ready(function() {
$('.dbcol').live('click', function () {
var str = "";
str = $(this).closest("ul").attr("id");
var master_name = "";
if (str == "countryselect") {master_name = "Country_Master"}
if (str == "stateselect") {master_name = "State_Master"}
if (str == "locationselect") {master_name = "Location_Master"}
if (str == "hotelselect") {master_name = "Hotel_Master"}
var $newelement = "";
$newelement += '<span class="label label-info isr" style="margin-top:3px; margin-bottom:2px; margin-right:5px; margin-left:3px; padding:2px;" id = ' +str+ '>';
$newelement += master_name + '.';
$newelement += $(this).text() + " ";
$newelement += '<i class="icon-remove icon-white"></i>';
$newelement += '</span>';
$(this).remove();
$("#selectedtags").append($newelement);
});
$("i").hover(
function () {
$(this).removeClass('icon-white');
});
$('i').live('click',function() {
var id = '#'
id += $(this).closest("span").attr("id");
var trt = $(this).closest("span").text();
trt = trt.substring(trt.indexOf('.')+1);
$(id).append('<li class="dbcol">' + trt +'</li>');
$(this).closest("span").remove();
});
$("#delegatecontent").live('click',function() {
var strqw ="";
var final_string = "Select ";
$('.isr').each( function() {
var df = $(this).text();
if (strqw == ""){
strqw += df;
}
else
{
strqw += ', ';
strqw += df;
}
});
final_string += strqw;
alert (final_string);
});
});
Everything works fine, Jquery code do append the newly created span tags in the div however the new tags goes out of the div width (span9) instead of going in the next line.
In addition to the default bootstrap style, following is added:
body {padding-top: 40px; padding-bottom: 40px; font-family: 'Monda', sans-serif;}
ul li {cursor: pointer;}
Help Please. Thanks
class label label-info is causing the issue here.
$newelement += '<span class="label label-info isr" style="margin-top:3px; margin-bottom:2px; margin-right:5px; margin-left:3px; padding:2px;" id = ' +str+ '>';
$newelement += master_name + '.';
$newelement += $(this).text() + " ";
$newelement += '<i class="icon-remove icon-white"></i>';
$newelement += '</span>';
I am using the bootstrap class "label label-info" to style the newly created span tags.
If i remove the class label label-info the code works fine.
$newelement += '<span class="isr" style="margin-top:3px; margin-bottom:2px; margin-right:5px; margin-left:3px; padding:2px;" id = ' +str+ '>';
$newelement += master_name + '.';
$newelement += $(this).text() + " ";
$newelement += '<i class="icon-remove icon-white"></i>';
$newelement += '</span>';
I am using a custom style now for span tags.
Thanks for help.
Try overflow:hidden style on "selectedtags" div.
ie
<div class="span9">
<div id = "selectedtags" class="well" style='overflow:hidden'>
</div>
<button class="btn" type="button" id="delegatecontent">Create report</button>
</div>

Categories