Different datas for each element inside vue-for cycle - laravel

I'm new to Vue and since my start some week ago I find myself really happy about it and the way it can be combined with pure javascript.
I'm running this code inside a laravel blade template:
<template v-for = "background in backgrounds" >
<template v-if="currentBackground.path === background.path">
<div class="m-1 background inline-block rounded-circle" style="width: 100px; height: 100px; overflow: hidden">
<img class="img-fluid " :src="background.path" v-on:click="changeBack(background)" :style="circledPositionStyle" v-on:load="inquadraThumb(background)">
</div>
</template>
</template>
And in the script section:
data() { return {
[...]
frontObjects : '',
circledPositionStyle : '' }},
methods: {
[...],
inquadraThumb(back) {
var thumbHeight = 100;
var calculatedThumbPositionY = (back.Ypos * thumbHeight) / 500;
var calculatedThumbPositionX = (back.Xpos * calculatedThumbPositionY) / back.Ypos;
this.circledPositionStyle = "transform: scale(4); height: " + thumbHeight + "px;transform-origin:" + calculatedThumbPositionX + "px " + calculatedThumbPositionY + "px;";
},
Now, the code works just fine, but all the images generated in the loop have the same circledPositionStylestyle applied... How can I manage to have different values for each cycle?

You are referencing circlePositionStyle as the data property, so if that value changes, it will change for every item that refers to it.
Instead, change your function to return the value of curclePositionStyle instead of mutating the data property.
inquadraThumb(back) {
var thumbHeight = 100;
var calculatedThumbPositionY = (back.Ypos * thumbHeight) / 500;
var calculatedThumbPositionX = (back.Xpos * calculatedThumbPositionY) / back.Ypos;
return "transform: scale(4); height: " + thumbHeight + "px;transform-origin:" + calculatedThumbPositionX + "px " + calculatedThumbPositionY + "px;";
}
You will also need to slightly adjust the tag:
<img class="img-fluid " :src="background.path" v-on:click="changeBack(background)" :style="inquadraThumb(background)">

Related

drag, resize and rotate with mouse

I need to be able to resize, rotate, and move an image. I have managed to find the code below that works but I need to either have a rotation point on the image where I can use it to rotate it with mouse or have the slider to move with the image. The problem starts when the image and the slider are too far apart. I would prefer to have the slider as part of the image if possible, somehow connected. Many thanks in advance for your help. The image is a protractor where it needs to be moved and rotated to measure angles.
Below is my codes
HTML
<!-- Mockup img downloaded from www.magicmockups.com -->
<!-- Change the mockup image to any image of your choice in the img tag bellow. -->
<!-- XXX: WARNING: When the pen is saved, the movable div is RESET to the original
position/size/rotation. -->
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</div>
<div style="margin-top: 20px">ROTATION SLIDER:</div>
<div id="slider" style="display:inline-block; width: 50%; margin: 10px 0 10px1 0px;">
</div>
<div style="display: inline-block; position: relative;">
<!-- CHANGE IMG TO YOUR IMG -->
<div id="movable" >https://link to image</div>
Javascript
var currentUnit = "pixels"
$( function() {
$("input[type=radio]").checkboxradio();
$("#slider").slider({
min: -360,
max: 360,
slide: function(event, ui) {
// Set the slider's correct value for "value".
$(this).slider('value', ui.value);
$("#movable").css('transform', 'rotate(' + ui.value + 'deg)')
updateText()
}
});
$("#movable").draggable({
drag: function(event, ui) {
updateText()
}
})
$("#movable").resizable({
resize: function(event, ui) {
updateText()
}
})
// Init the text.
updateText();
});
function getPixelDimensions() {
precision = 100
// Save current transform (rotation).
originalTransform = $("#movable").css('transform')
// Remove rotation to make sure position() is the CSS position, not the bounding rect
position.
$("#movable").css('transform', 'rotate(0deg)')
position = $("#movable").position()
// Restore rotation.
$("#movable").css('transform', originalTransform)
dim = {
top: Math.round(position.top * precision) / precision,
left: Math.round(position.left * precision) / precision,
width: Math.round($("#movable")[0].clientWidth * precision) / precision,
height: Math.round($("#movable")[0].clientHeight * precision) / precision
}
return dim;
}
function getPercentageDimensions() {
}
function updateText() {
if(currentUnit == "pixels") {
dim = getPixelDimensions();
sufix = "px"
} else {
dim = getPercentageDimensions();
sufix = "%"
}
$(".d").remove()
for(prop in dim) {
$("#dimensions").append( "<div class='d'>" + prop + ": " + dim[prop] + sufix + "</div>");
}
$("#dimensions").append( "<div class='d'>rotate: " + $("#slider").slider("value") +
"deg</div>");
//console.log($("#outer").position().top)
}
$('input').change(function() {
if(this.id == "radio-1") {
currentUnit = "pixels";
updateText();
} else if(this.id.search("radio") != -1){
currentUnit = "percentage";
updateText();
}
})
function previewFile() {
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
CSS
#movable {
position: absolute;
text-align: center;
/*Manually change values here.*/
width: 400px;
height: 400px;
top: 0px;
left: 0px;
transform: rotate(0deg);
}

webRTC socket.io error transport unknown

I get following error from the socket.io server.
"Transport unknown"
Can you please tell me why it's giving this error?
I using this Signalling server Connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
My code used to work before but suddenly it stopped working.
Using this library to implement webRTC
http://www.rtcmulticonnection.org/docs/
Can anyone help me with this?
Following is my code
<script src="https://cdn.webrtc-experiment.com:443/rmc3.min.js"></script>
<script type="text/javascript">
var Connection = new RTCMultiConnection();
// or a free signaling server
Connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
Connection.session = {
data: true,
audio: true,
};
Connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
localvideoContainer = document.getElementById('meeting-preview');
remotevideoContainer = document.getElementById('attendee-xylon');
Connection.onstream = function(event){
var video = event.mediaElement;
console.log(event);
if (event.type === 'local') {
var userinfoDIV = document.createElement('div');
userinfoDIV.className = 'user-video';
userinfoDIV.innerHTML = '<video id="' + event.userid + '" src="' + URL.createObjectURL(event.stream) + '" autoplay muted=true volume=0></vide>' || '<img src="/frontend/images/meeting-preview.png" class="img-responsive" />';
localvideoContainer.appendChild(userinfoDIV);
};
if (event.type === 'remote') {
var userinfoDIV = document.createElement('div');
userinfoDIV.id = event.userid;
userinfoDIV.className = 'user-video meeting-attendees-content timer-icon';
userinfoDIV.innerHTML = '<div id="remote"><video id="' + event.userid + '" src="' + URL.createObjectURL(event.stream) + '" autoplay muted=true volume=0></vide></div><button class="btn btn-custom" type="button" data-toggle="collapse" data-target="#collapse-one" aria-expanded="false" aria-controls="collapse-one">Show Goals / Progress</button><div class="collapse" id="collapse-one"><div class="well attendees-moreinfo"><div class="row"><div class="col-lg-12"><div class="personality-label week-goal"><span>1.</span> Here comes my defined goal for the week</div><div class="personality-bar"><div class="goal-bar-wrap"><div class="meter goal-progress nostripes"><span style="width: 66px; height: 4px;"></span></div></div></div><div class="personality-percentage text-right"><p>66%</p><p></p></div></div></div><div class="row"><div class="col-lg-12"><div class="personality-label week-goal"><span>2.</span> Here comes my defined goal for the week</div><div class="personality-bar"><div class="goal-bar-wrap"><div class="meter goal-progress nostripes"><span style="width: 50px; height: 4px;"></span></div></div></div><div class="personality-percentage text-right"><p>50%</p><p></p></div></div></div><div class="row"><div class="col-lg-12"><div class="personality-label week-goal"><span>3.</span> Here comes my defined goal for the week</div><div class="personality-bar"><div class="goal-bar-wrap"><div class="meter goal-progress nostripes"><span style="width: 80px; height: 4px;"></span></div></div></div><div class="personality-percentage text-right"><p>80%</p><p></p></div></div></div></div></div>' || '<img src="/frontend/images/meeting-preview.png" class="img-responsive" />';
remotevideoContainer.appendChild(userinfoDIV);
};
}
Connection.onclose = Connection.onleave = function(event) {
console.log(event);
$('#'+event.userid).hide();
};
</script>
<script type="text/javascript">
$(document).ready(function(){
var url = window.location.pathname;
Connection.openOrJoin(url.replace('/meetings/joinMeeting/',"") || 'predefined-roomid');
});
</script>
Please check this:
https://github.com/muaz-khan/RTCMultiConnection/releases/tag/3.4.2
Recent release is using latest socket.io.js, so you're asked to use following files instead:
<script src="https://rtcmulticonnection.herokuapp.com/dist/RTCMultiConnection.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/socket.io/socket.io.js"></script>
Please do NOT use rmc3.min.js.

jquery dataTable filter with single char not working

One of the column value are single char for each row, I need to apply the filter with checkbox, the filer is not working, but it working fine if column value is more than 1 char.
// define the DaataTable dataTableObj, the table id is 'my_DataTable_Id' for example
"aoColumns":
[
{title:'<th style="font-size: 100%; width: 4%;min-width: 40px;" ><font>Name</font></th>'},
{title:'<th style="font-size: 100%; width: 7%;min-width: 70px;"><font>Area</font></th>',"sType": 'numeric'},
{title:'<th style="font-size: 100%; width: 5%;min-width: 30px"><font>Dept</font></th>',"sType": 'numeric'}, // This is single value column
{title:'<th style="font-size: 100%; width: 5%;min-width: 30px"><font>Note</font></th>'}
]
var cExtraChar = "X";
var columnArray = [];
// Start loop - to get an json dataObject from list of object
columnArray[0] = '<td style="height:40px; width:10%;"> <input type="text" id="NAME_'+index+'" style="border:0;" value='+data[index].Name+'></input> </td>';
columnArray[1] = '<td style="height:40px; width:10%;"> <input type="text" id="AREA_'+index+'" style="border:0;" value='+data[index].Area+'></input> </td>';
// This is single char value column like Dept either one of 'A', 'B', 'C', 'D'
// it has Single char value, it not support in dataTable filtering, so add hiden span to add comman extra char for each row.
columnArray[2] = '<td style="height:40px; width:10%;"> <input type="text" id="DEPT_'+index+'" style="border:0;" value='+data[index].Dept+'></input> </td>' +
'<span style="visibility: hidden; display: none;">' + cExtraChar+data[index].Dept + '</span> </td>';
columnArray[3] = '<td style="height:40px; width:10%;"> <input type="text" id="NOTE_'+index+'" style="border:0;" value='+data[index].Note+'></input> </td>';
dataTableObj.fnAddData(columnArray,false);
// End loop
var aAreaFilters = data.AreaList; // It can dynamic values from response
var aDeptFilters = ['A', 'B', 'C', 'D']; // It also dynamic values from response
dataTableObj.columnFilter(
{
sPlaceHolder: "head:before",
aoColumns:
[ null,
{type:"checkbox", values: aAreaFilters},
{type:"checkbox", values: aDeptFilters},
null
]
}
);
dataTableObj.fnDraw();
// Finally change the filter check box value (not lable value) for the column Dept.
for(var i = 0; i < aDeptFilters.length; i++) {
var targetID = "my_DataTable_Id_cb_" + aDeptFilters[i];
var targetVal = cExtraChar + aDeptFilters[i];
$("#"+targetID).val(targetVal);
}

How to put an if condition under columns in kendo grid

Can we add a if Condition inside the column while describing the columns of the grid? Whats wrong in this code
I want to display one button in the grid under a column ,if length of the text exceeds more than 40char.
I am trying to put an if condition if the content/data is less than 40 char then display the content else display a button , On click of button open a pop-up to display the complete content inside that pop-up?
How we can put the command conditionally to display the button?
Here is my code
columns: [{
field: "id",
title: "ID",
width: "100px"
}, // fields in the grid
{
field: "name",
title: "Name",
width: "100px"
}, {
field: "remarks",
title: "Remarks",
width: "160px", // under this column button will be displayed in each
var length = 40;
if (data.remarks.length > length) { //here this condition seems to be wrong, is there any other way to display the button for this condition
command: {
name: "remarks",
text: "Remarks",
click: function (e) {
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
var win = $('#remarksWindow');
win.html(data.remarks);
if (!win.data('kendoWindow')) {
win.kendoWindow({
width: '600px',
height: '200px',
title: 'Remarks',
actions: ['Close']
});
}
win.parent().css({
top: e.pageY - 50,
left: e.clientX - 640,
width: '600px',
height: '200px'
});
win.data('kendoWindow').open(); // open the pop-up which contains the data
return false;
}
}
}
}
},
First of all, you have a syntax error in JavaScript. Note that you can't put statements or declarations between the properties of an object:
var obj = {
a: 1,
if (true) {
b: 2;
}
}
Or
var obj = {
a: 1,
var b = 1;
}
The examples above doesn't works. So in your column property you have to use a template property:
{
field: "remarks",
title: "Remarks",
width: "160px",
template: "" // <- here goes your logic
}
So a simple template can be set as a string containing html with JavaScript logic, e.g.:
# if (remarks.length > 40) { # <input type='button' class='btn-remarks' /> # } #
Yes, you will have to set the button html by yourself. There is no way to add a condition to a command button(and that is a shame, actually).
You can check how template works here.
Then your column item should be:
{
field: "remarks",
title: "Remarks",
width: "160px",
template: "# if (remarks.length > 40) { # <input type='button' class='remarks' /> # } #"
}
Then you have to set the event for all your buttons(probably in the dataBound event):
$("#yourGrid").on("click", ".btn-remarks", function()
{
// all your click logic here
});
Give it a try and tell me what happens.
Hopefully this dojo is what you are looking for: http://dojo.telerik.com/ETora
(I have used one of Telerik's grid demos and modified to show you the principles)
The functionality you are looking for can be achieved by two means:
1) Apply a client Template to the column
2) Add a databound event that then hooks up the buttons
columns:[ {
field: "CompanyName",
title: "Company Name",
template: "#= displayTextorButton(data.CompanyName) #"
}]
function displayTextorButton(data){
var retString = '';
console.log(data);
if(data !== null && data !== undefined)
{
if(data.length > 20)
{
retString = ' <button type="button" class="btn btn-xs btn-primary"' +
'data-toggle="popover" data-placement="auto right" data-container="body" ' +
'data-content="' + kendo.htmlEncode(data) + '"' +
'data-title="Running Log Information" data-trigger="click" data-role-me="content-popover" > <span class="glyphicons glyphicons-pencil"></span> View</button>';
}
else
{
retString = '<span>' + data + '</span>';
}
}else
{
retString = '<span> - </span>';
}
return retString;
}
so the first bit I have done is added a template to the Company Name column that checks if the name is more than 20 characters if it is then it will display a button if it isn't then it will display the text as normal.
function(e){
$('button[data-role-me="content-popover"]').popover({ trigger: "focus", html: true });
}
I then hook up a databound event to the grid to then attach the event features to the "pop up" in my sample
Also note I have hooked in the bootstrap features just to make things a little easier for the demo. So this is using their popover feature. You could modify this code to work with your window.
Any issues let me know.
This is the kendo grid code
{ field: "marks", title: "marks",width: "160px",
template: function(dataItem) {
var marks = dataItem.marks;
var retString = '';
if(marks !== null && marks !== undefined)
{
if(marks.length > 40)
{
marks1 = marks.substring(0, 40)+'...';
retString1 ='<span>'+ marks1 +'</span>';
retString = retString1 + ' <button id="marksButton" type="button"' +
'data-toggle="popover" data-placement="auto right" data-container="body" ' +
'data-content="' + kendo.htmlEncode(addlRemarks) + '"' +
'data-title="marks" data-trigger="click" data-role-me="content-popover" > marks</button>';
}
else
{
retString = '<span>' + marks + '</span>';
}
}else
{
retString = '<span> - </span>';
}
return retString;
}
And its being called from a HTMl
<div class="panel-body" ng-show="accOpen[$index]">
<!-- Marks TABLE -->
<div marks-table=""
accordion-flag="accOpen[$index]"
name="name"
id="id"
>
</div>
</div>

Jquery Datatable sorting

I'm noob with Jquery DataTables.
I have a very basic question on how to use the sorting plugins:
Have googled a lot on this, but I fail to get proper answers, on how to incorporate them in my code, do we have to just add the script to a ".js" file and add it? or Do we also have to call the function of the plugins?
Can someone point me to a working example with sorting of numeric columns formatted with commas/percentage signs.
The columns with signs or commas are sorted as string. I have seen a lot of references which say to use plugins and then specify sType or sSortableDataType but that doesn't work.
Here's my code: (Please correct me where I'm wrong)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="scorecard_dynamic.aspx.cs" Inherits="Dashboard_scorecard_dynamic" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>new score card</title>
<%--<script src="../js/jquery-1.10.2.min.js"></script>--%>
<style type="text/css" title="currentStyle">
#import "../js/datatable/css/demo_page.css";
#import "../js/datatable/css/demo_table.css";
</style>
<script type="text/javascript" src="../js/datatable/js/jquery.js"></script>
<script type="text/javascript" src="../js/datatable/js/jquery.dataTables.js"></script>
<script src="../js/datatable/Plugins-master/sorting/custom-data-source/percent.js"></script>
<link href="../StyleSheet/LoadingPanel.css" rel="stylesheet" />
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
gettopchannelsplot();
//transpose();
var otable = $('#example').dataTable({
"iDisplayLength": 5,
"aLengthMenu": [[1, 2, 3, 4, 5], [1, 2, 3, 4, "All"]],
"oLanguage": {
"oPaginate": {
"sPrevious": "Previous", //can change text for pagination
"sNext": "Next"
},
//"fnDrawCallback": function (oSettings) {
// alert('DataTables has redrawn the table');
//},
"aoColumns": [
null,
{ "sType": "pct" },
null,
null,
null,
null,
null,
null
],
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0,5,6,7 ] }
]
}
//"sPaginationType": "full_numbers"
});
oTable.fnSort([[3, 'asc']]);
});
var StartDate = '16-oct-2013';
var EndDate = '22-oct-2013';
function transpose() {
var t = $('#example tbody').eq(0);
var r = t.find('tr');
var cols = r.length;
var rows = r.eq(0).find('td').length;
var cell, next, tem, i = 0;
var tb = $('<tbody></tbody>');
while (i < rows) {
cell = 0;
tem = $('<tr></tr>');
while (cell < cols) {
next = r.eq(cell++).find('td').eq(0);
tem.append(next);
}
tb.append(tem);
++i;
}
$('#example').append(tb);
$('#example').show();
}
function gettopchannelsplot() {
//$("#bubbling").show();
//alert('gettopchannelsplot');
var arrListMain = new Array();
var arrList = new Array();
var linkName = 'View Chatter';
var result = ExecuteSynchronously('../SocialMedia.asmx', 'GetTopchannels', { startDate: StartDate, endDate: EndDate });
//tbl_example.empty();
$('#example thead').append("<tr>"
+"<td class='normalBold' align='left'>info</td>"
+ "<td class='normalBold' align='left'>share of voice</td>"
+ "<td class='normalBold' align='left'>total chatter</td>"
+ "<td class='normalBold' align='left'>sentiments</td>"
+ "<td class='normalBold' align='left'>exposure</td>"
+ "<td class='normalBold' align='left'>most popular with</td>"
+ "<td class='normalBold' align='left'>most popular on</td>"
+ "<td class='normalBold' align='left'>link</td>"
+ "</tr>");
var value = new Array();
if (result.d != "" && result.d != null) {
arrListMain = result.d.split('#');
for (var i = 0; i < arrListMain.length; i++) {
var tmp = "<tr>"
+ "<td class='border' width='12%'><a href='../Scorecard.aspx?1'><image src='" + "../" + arrListMain[i].split('^')[7] + "'/></a></td>"
+ " <td class='border' width='12%' align='center'>" + arrListMain[i].split('^')[2] + "%</td>"
+ " <td class='border' width='12%' align='center'> " + arrListMain[i].split('^')[3] + "</td>"
//// + " <td class='border' width='12%' align='center'><label id=label" + i + " >" + Number(arrListMain[i].split('^')[3]).toLocaleString() + "</label></td>"
+ " <td class='border' width='12%' align='center'><image src='" + "../" + arrListMain[i].split('^')[10] + "'/></td>"
+ " <td class='border' width='13%' align='center'>" + arrListMain[i].split('^')[5] + "</td>"
+ " <td class='border' width='13%' align='center'><image src='" + "../" + arrListMain[i].split('^')[8] + "'/></td>"
+ " <td class='border' width='13%' align='center'><image src='" + "../" + arrListMain[i].split('^')[9] + "'/></td>"
+ " <td class='border' width='13%' align='center'><a href='../ChatterAdvanced2.aspx?filter=channel&value=" + arrListMain[i].split('^')[0] + "'>chatter</a></td>"
+ "</tr>";
//alert(tmp);
$('#example tbody').append(tmp);
}
}
$("#bubbling").hide();
}
</script>
<script type="text/javascript">
function ExecuteSynchronously(url, method, args) {
var executor = new Sys.Net.XMLHttpSyncExecutor(); // Instantiate a WebRequest.
var request = new Sys.Net.WebRequest(); // Set the request URL.
request.set_url(url + '/' + method); // Set the request verb.
request.set_httpVerb('POST'); // Set request header.
request.get_headers()['Content-Type'] = 'application/json; charset=utf-8'; // Set the executor.
request.set_executor(executor); // Serialize argumente into a JSON string.
request.set_body(Sys.Serialization.JavaScriptSerializer.serialize(args)); // Execute the request.
request.invoke();
if (executor.get_responseAvailable()) {
return (executor.get_object());
}
return (false);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<AjaxToolkit:ToolkitScriptManager runat="server" ID="ASD">
<Scripts>
<asp:ScriptReference Path="~/js/XMLHttpSyncExecutor.js" ScriptMode="Release" />
<asp:ScriptReference Path="~/App_Code/SocialMedia.cs" />
</Scripts>
</AjaxToolkit:ToolkitScriptManager>
<div>
<div class="bubblingG" id="bubbling">
<span id="bubblingG_1"></span>
<span id="bubblingG_2"></span>
<span id="bubblingG_3"></span>
</div>
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
Please excuse my HTML markup formatting.
You need both the "plugin" and set the proper sType according to that plugin. The plugins are really just some very simple functions, that you easily can produce yourself for your own needs and place into your code. Consider this "plugin" that sort percents with commas :
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"normalize": function(n) {
return parseFloat(n.toString().replace(',','.'));
},
"percent-asc": function(a, b) {
a=this.normalize(a);
b=this.normalize(b);
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"percent-desc": function(a, b) {
a=this.normalize(a);
b=this.normalize(b);
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
The above is pretty failsafe. To initialize :
var dataTable = $('#example').dataTable({
aoColumns: [
null,
null,
null,
{ sType: "percent" },
null
],
//...
});
see this working fiddle demonstrating the code above -> http://jsfiddle.net/xK7Ud/

Resources