Add a "Show Less" button to InstafeedJS - javascript

Using InstafeedJS, I want to be able to add a button that hides whatever content has been loaded after the initial feed (e.g. the user has clicked Show More one or more times). My initial idea is to add a class or data tag to the additional feed items, then hide them with a custom button. But I'm not sure how to add these references through the script. Any ideas?
Current code:
var loadButton = document.getElementById('instafeed-loadmore');
var feed = new Instafeed({
get: 'user',
type: 'image',
limit: '5',
sortBy: 'most-recent',
resolution: 'standard_resolution',
userId: <?php echo $instagram_id; ?>,
accessToken: '<?php echo $instagram_token; ?>',
template: '<li><span class="instagram-post" data-url="{{link}}" data-modal="instagram-popup" data-caption="{{caption}}" data-image="{{image}}" style="background-image: url({{image}});"></span></li>',
after: function() {
if (!this.hasNext()) {
loadButton.setAttribute('disabled', 'disabled');
}
}
});
loadButton.addEventListener('click', function() {
feed.next();
});
feed.run();

While Dipen's answer is great, as you don't seem to be using jQuery, here it is in standard Js
var limit = 4;
var feed = new Instafeed({
target: 'instafeed',
get: 'user',
type: 'image',
sortBy: 'most-recent',
limit: limit,
resolution: 'standard_resolution',
userId: <?php echo $instagram_id; ?>,
accessToken: '<?php echo $instagram_token; ?>',
template: '<img class="instagram-post" src={{image}} />',
after: function() {
if (!this.hasNext()) {
document.getElementById('btnMore').attr('disabled', 'disabled');
}
}
});
document.getElementById('btnMore').on('click', function(e) {
document.getElementsByClassName("instagram-post:nth-child(n+" + (1 + limit) + ")").show();
feed.next();
});
document.getElementById('btnLess').on('click', function(e) {
document.getElementsByClassName("instagram-post:nth-child(n+" + (1 + limit) + ")").hide();
});
feed.run();
(P.S. As I only de "JQueryified" it for you accept his as the answer, not mine.)

You can add references through the script or add custom data attribute on loaded elements (there are more than one way to achieve what you want) but in my opinion you can use CSS selector to select all elements loaded after initial feed and apply some style (hide) them as shown in the code snippet below.
var limit = 4;
var feed = new Instafeed({
target: 'instafeed',
get: 'user',
type: 'image',
sortBy: 'most-recent',
limit: limit,
resolution: 'standard_resolution',
userId: <?php echo $instagram_id; ?>,
accessToken: '<?php echo $instagram_token; ?>',
template: '<img class="instagram-post" src={{image}} />',
after: function() {
if (!this.hasNext()) {
$('#btnMore').attr('disabled', 'disabled');
}
}
});
$('#btnMore').on('click', function(e) {
$(".instagram-post:nth-child(n+" + (1 + limit) + ")").show();
feed.next();
});
$('#btnLess').on('click', function(e) {
$(".instagram-post:nth-child(n+" + (1 + limit) + ")").hide();
});
feed.run();
.instagram-post {
width: 100px;
height: 100px;
display: inline-block;
margin: 15px;
}
<div id="instafeed"></div>
<button id="btnMore">Load More...</button>
<button id="btnLess">Show Less...</button>
Modify the code as per your need.
Exaplanation:
In the click event handler of $('#btnLess') I'm selecting all images with class .instagram-post from index limit + 1 and hiding them.
In the click event handler of $('#btnMore') I'm making sure all of the available images in the feed are visible so that whenever I press it after pressing $('#btnLess') all previously loaded images in the feed are visible as well.
Hope it helps.

Related

How can I send data to controller by dialog?

EDIT2: I'm trying to update my code with java, but it's not working (I suppose I miss something in controller):
$(document).ready(function() {
var listGraphic = new Array();
function addPhoto(u, d) {
$.ajax({
url: "aggiungiEpigrafe",
type: "POST",
data: {"graphicUrl": u, "graphicDesc": d},
success: function(data) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc, "<br /><br />");
$(this).dialog("close");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$("#newPhoto").submit(function(e) {
e.preventDefault();
var url = $("#graphicUrl").val();
var desc = $("#graphicDesc").val();
listGraphic.push(url);
listGraphic.push(desc);
console.log(listGraphic);
addPhoto(url, desc);
$("#graphicUrl").val("");
$("#graphicDesc").val("");
if ($('#insertPhoto').dialog("isOpen")) {
$('#insertPhoto').dialog("close");
}
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
$("#newPhoto").submit();
}
}
});
});
EDIT1:
Following Twisty suggestion I uptaded the dialog in order to not have any form inside (since this dialog is already in a form): https://jsfiddle.net/e57sj6hp/18/
As Twisty was also commenting, I probably need ajax, but I have to understand how use it; I think I need to use serialize() or seralizeArray(), but I don't understand well how should the controller receive the json and use it.
I have a controller like this:
public String myMethod(#ModelAttribute MyObject object, ModelMap model){...}
The object include a List of photos, and two variables url and description:
List<Photo> photos;
String url;
String description;
each photo in the list is formed by an url and a description.
In my jsp I created a dialog with jquery where a user can put an url and a description, what I want to do is to add each value into a list and send it to the controller, then clean the dialog in order to allow another submission.
I have tried a lot of but can't understand how I should do it. I'm using the spring's form and I have tried many different ways, but I think that the problem is in my javascript code. Here's one example: https://jsfiddle.net/e57sj6hp/12/
In this example the input fields and the textarea inside the dialog aren't surrounded with spring's form tags, since I've append the result inside the div and I supposed that, at the moment of the submitting, the controller should receive the data inside the form:input just created.
Not familiar with Spring, so I may miss an element, but matching what you put in your example, I can offer some potential updates.
Working Example: https://jsfiddle.net/Twisty/e57sj6hp/16/
HTML Updated
<div id="insertPhoto" style="display:none" title="Insert a Photo">
<form id="newPhoto">
<label>Url:</label>
<br/>
<input id="graphicUrl" />
<br/> Description:
<br/>
<textarea rows="4" cols="20" id="graphicDesc"></textarea>
</form>
</div>
You cannot call form.reset() without a form element. I wrapped the the form elements in a form. This has the added benefit of now responding to the form being submitted, for example if the user enters a url and hits enter.
jQuery
$(document).ready(function() {
var listGraphic = new Array();
function addPhoto(u, d) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc);
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$("#newPhoto").submit(function(e) {
e.preventDefault();
var url = $("#graphicUrl").val();
var desc = $("#graphicDesc").val();
listGraphic.push(url);
listGraphic.push(desc);
console.log(listGraphic);
addPhoto(url, desc);
$(this)[0].reset();
if ($('#insertPhoto').dialog("isOpen")) {
$('#insertPhoto').dialog("close");
}
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
$("#newPhoto").submit();
}
}
});
});
Lots of little fixes and improvements here. I moved listGraphic out of the functions, so it can be updated more globally. This allows it to be updated and read from other callbacks.
I created the function to make it a little easier to repeat.
Now regardless of how the form is submitted, the array is updated and so is the page. The dialog is closed and it's form is reset.
UPDATE 1
See new jQuery: https://jsfiddle.net/Twisty/e57sj6hp/21/
jQuery
$(document).ready(function() {
function addPhoto(u, d) {
$.ajax({
url: "aggiungiEpigrafe",
type: "POST",
data: JSON.stringify({
"graphicUrl": u,
"graphicDesc": d
}),
complete: function(data) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc, "<br /><br />");
}
});
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
addPhoto($("#graphicUrl").val(), $("#graphicDesc").val());
// Reset values
$("#graphicUrl").val("");
$("#graphicDesc").val("");
// Close Dialog
$(this).dialog("close");
}
}
});
});

how to get values from db and insert them to events array

My code is as below.
<script>
var t=<?php echo json_encode($ta)?>;
var d=<?php echo json_encode($da)?>;
$(document).ready(function() {
$('#calendar').fullCalendar({
//defaultDate: '2016-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
//$r=$ev->title;
for(var j=0;j<d.length;j++)
{
events: [{
title: t[j],
start: d[j]
}
]
}
});
});
</script>
I have used the fullcalendar 2.6.1. But nothing displayed. Please can anybody help me? I want to retrieve all the title and eventDate from the db and view in the calendar. The var t and d contains the all the data of $ta and $da arrays. I just wanted to assign them to events array title and start keywords.There are some red marks indicate that for loop is going to be wrong.
Try this one
<?php
$ta=array();
$i=0;
?>
#foreach($events as $ev)
<?php
$ta[$i]['title'] = $ev->title;
$ta[$i]['start'] = date('Y-m-d H:i:s', strtotime($ev->eventDate));
$i++;
?>
#endforeach
<script>
var t=<?php echo json_encode($ta)?>;
$(document).ready(function() {
$('#calendar').fullCalendar({
//defaultDate: '2016-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
events: t,
eventRender: function(event, element) {
$('.fc-time', element).hide();
}
});
});
</script>
$.ajax({
url:'',
dataType: 'json',
success: function(doc) {
var events = [];
$.each(doc, function(key, value){
events.push({
title : value['title name'],
start : value['hours'],
backgroundColor: Metronic.getBrandColor('yellow'),
id : value['id']
});
});
AddFullCalenderEvent(events);
}
});
function AddFullCalenderEvent(eventList){
$('#calendar').fullCalendar({
events: eventList,
eventClick: function(event) {
// opens events in a popup window
window.location.href = "pagename?id=" + event.id;
return false;
}
Try this

add option to select dynamically using jqtransform

I am using the plugin jqtransform to dynamically add options to a select using Ajax. Here I leave my script. Could you tell me what I have to do to see my new options?
<script type="text/javascript" >
var path = '<?php echo base_url() ?>';
$(document).on('ready', function() {
cargarJugadores();
$('#equipos').change(cargarJugadores);
});
function cargarJugadores() {
var codEquipo = $('#equipos').val();
$.getJSON(path + 'traspasos/devuelveJugadoresPorId', {id: codEquipo}, function(resp) {
console.log("->", resp);
$('#jugadores').empty();
$.each(resp, function(indice, valor) {
option = $('<option></option>', {
text: valor,
value: indice
});
$('#jugadores').append(option);
});
});
$('#jugadores').jqTransSelect(true);
}
</script>

How can i check number of files selected with Fine Uploader?

I am using manual uploading via Fine Uploader. Now i want to check that file has selected or not.
$(document).ready(function() {
var fineuploader = new qq.FineUploader({
element: $('#fine-uploader')[0],
request: {
endpoint: '<?php echo site_url('pl_items/upload_images');?>'
},
multiple: true,
autoUpload: false,
onLeave: false,
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
sizeLimit: 5120000 // 50 kB = 50 * 1024 bytes
},
text: {
uploadButton: '<i class="icon-plus icon-white"></i> Select Files'
},
template: '<div class="qq-uploader">' +
'<pre class="qq-upload-drop-area"><span>{dragZoneText}</span></pre>' +
'<div class="qq-upload-button btn btn-danger">{uploadButtonText}</div>' +
'<div class="qq-drop-processing span1"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></div>' +
'<div><ul class="qq-upload-list"></ul></div>' +
'</div>',
callbacks: {
onComplete: function(id, name, response) {
$('#frmDetails').append('<input type="hidden" name="pl_item_images[]" value="'+response.file_name+'">');
//$("#frmDetails").submit();
}
},
});
$('#submit_button').click(function() {
fineuploader.uploadStoredFiles();
});
});
Since you haven't responded to my question, I'll just assume that you want to determine if a file has been selected before you call uploadStoredFiles in your click handler.
It's really very simple. Just make use of the getUploads API method. For example, you could change your click handler to look like this:
$('#submit_button').click(function() {
var submittedFileCount = fineuploader.getUploads({status: qq.status.SUBMITTED}).length;
if (submittedFileCouunt > 0) {
fineuploader.uploadStoredFiles();
}
});
A few more things:
There is no onLeave option. You should remove this from your code.
The multiple option defaults to true. You can remove this from your code as well.
You are already using jQuery. Why aren't you using the Fine Uploader jQuery plug-in? See the documentation for instructions.

Ajax submit of data array in CakePHP not working

I'm making making a scheduling calendar where schedulers can drag and drop members of an organization onto Fullcalendar. I have gotten as far as storing dropped events in an array Object, arrayOfEvents. I want to make an Ajax submit to a CakePHP add function to insert the data into my events database and then reload the calendar. Here's my code.
External events to drop:
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()), // use the element's text as the event title
userId: this.id
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
Fullcalendar:
/* initialize the calendar
-----------------------------------------------------------------*/
var arrayOfEvents = [];
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,agendaDay'
},
defaultView: 'agendaWeek',
editable: true,
events: [
<?php foreach ($users as $user) {
foreach ($user['Event'] as $event):
?>
{
start: '<?php echo $event['start_date']; ?>',
end: '<?php echo $event['end_date']; ?>',
title: '<?php echo $event['title']; ?>',
allDay: false,
color: '#077169'
},
<?php endforeach;
}
?>
],
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.end = (date.getTime() + 3600000) / 1000; // default shift length is 1 hour
copiedEventObject.userId = originalEventObject.userId;
copiedEventObject.allDay = false;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// Push events into array
arrayOfEvents.push(copiedEventObject);
//todo: the calendar needs to insert events into the event calendar.
console.log(arrayOfEvents);
}
});
});
Update Schedule function called on a link:
function updateSchedule()
{
var arrayOfEvents = [];
//var data = "numOfEvents=" + arrayOfEvents.length; //original
var data = "numOfEvents=" + arrayOfEvents.length;
// You can get all events out of the array here
for (var i = 0; i < arrayOfEvents.length; i++) {
var event = arrayOfEvents[i];
data += "&id" + i + "=" + event.id
+ "&start" + i + "=" + event.start
+ "&end" + i + "=" + event.end;
}
// Make your ajax post here
$.ajax({
type: "POST",
url: "<?php echo $this->webroot; ?>events/add",
data: data,
success: function(response) {
alert('done!');
},
fail: function(response) {
alert("error");
}
});
Cakephp events/add function:
public function add() {
$this->autoRender = false;
if ($this->RequestHandler->isAjax()) {
Configure::write('debug', 0);
}
if (!empty($this->data)) {
if ($this->Event->save($this->data)) {
echo 'Record has been added';
} else {
echo 'Error while adding record';
}
}
}
I know this is a long one but any input would be well received.

Categories

Resources