Apply the same JavaScript on multiple div scroll - horizontal-scrolling

I found this simple horizontal scroll :
http://jsfiddle.net/Lpjj3n1e/
Its working fine, but if I duplicate the horizontal scroll, only the first scroll function well.
What can I do to the JavaScript to be applied on 2, 3 or any variable number of generated scrolls ?
$(function() {
var print = function(msg) {
alert(msg);
};
var setInvisible = function(elem) {
elem.css('visibility', 'hidden');
};
var setVisible = function(elem) {
elem.css('visibility', 'visible');
};
var elem = $("#elem");
var items = elem.children();
// Inserting Buttons
elem.prepend('<div id="right-button" style="visibility: hidden;"><</div>');
elem.append(' <div id="left-button">></div>');
// Inserting Inner
items.wrapAll('<div id="inner" />');
// Inserting Outer
debugger;
elem.find('#inner').wrap('<div id="outer"/>');
var outer = $('#outer');
var updateUI = function() {
var maxWidth = outer.outerWidth(true);
var actualWidth = 0;
$.each($('#inner >'), function(i, item) {
actualWidth += $(item).outerWidth(true);
});
if (actualWidth <= maxWidth) {
setVisible($('#left-button'));
}
};
updateUI();
$('#right-button').click(function() {
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos - 200
}, 800, function() {
debugger;
if ($('#outer').scrollLeft() <= 0) {
setInvisible($('#right-button'));
}
});
});
$('#left-button').click(function() {
setVisible($('#right-button'));
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos + 200
}, 800);
});
$(window).resize(function() {
updateUI();
});
});

Related

How do I add an inline HTML field to a Suitelet to hold html markup?

Edit: code updated
I am trying to follow along with this blogpost which shows how to create a Suitelet which has a formatted table https://followingnetsuite.com/2020/10/16/skip-freemarker-by-delivering-saved-search-results-in-a-suitelet/
The blog post references adding a inline html field to hold the html mark up. I have tried to add this to the code though I know I am way off:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search", "N/ui/serverWidget"], function (search, ui) {
function onRequest(context) {
if (context.request.method === "GET") {
var form = ui.createForm({ title: "freemarker test" });
function getIssues() {
var issues = new Array();
var mySearch = search.load({
id: "customsearchcustomerallview",
});
var myPages = mySearch.runPaged({ pageSize: 1000 });
for (var i = 0; i < myPages.pageRanges.length; i++) {
var myPage = myPages.fetch({ index: i });
myPage.data.forEach(function (result) {
var issue = {};
mySearch.columns.forEach(function (col, index) {
issue["column_" + index] = {
label: col.label,
text: result.getText(col),
value: result.getValue(col),
};
});
issues.push(issue);
});
}
return issues;
}
function formatIssues(issues) {
var html = new Array();
html.push('<table class="RPT">');
html.push("<thead>");
if (issues.length > 0) {
var issue = issues[0];
html.push("<tr>");
for (var i = 0; i < 20; i++) {
if (issue.hasOwnProperty("column_" + i)) {
var sortType = isNaN(
issue["column_" + i].text || issue["column_" + i].value
)
? "string"
: "float";
html.push(
'<th data-sort="' +
sortType +
'">' +
issue["column_" + i].label +
"</th>"
);
}
}
html.push("</tr>");
}
html.push("</thead>");
html.push("<tbody>");
issues.forEach(function (issue) {
html.push("<tr>");
for (var i = 0; i < 20; i++) {
if (issue.hasOwnProperty("column_" + i)) {
var vAlign = isNaN(
issue["column_" + i].text || issue["column_" + i].value
)
? "left"
: "right";
html.push(
'<td align="' +
vAlign +
'">' +
(issue["column_" + i].text || issue["column_" + i].value) +
"</td>"
);
} else {
break;
}
}
html.push("</tr>");
});
html.push("</tbody>");
html.push("</table>");
return html.join("\n");
}
var htmlField = html.addField({
id: "custpage_html",
label: "html",
type: ui.FieldType.INLINEHTML,
});
htmlField.defaultValue = formatIssues(getIssues());
context.response.writePage(form);
}
}
return {
onRequest: onRequest,
};
});
I can't see the correct way to add this though. Where do I add the inline html field?
For a Suitelet, does the 'context.response.writePage(form)' need to be at the end of the rest of the code? (i.e. after the function that relates to the html markup?
Thanks
Add your HTML via the defaultValue property of the Inline HTML Field.
Structure your script as follows:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search", "N/ui/serverWidget"], function (search, ui) {
function onRequest(context) {
if (context.request.method === "GET") {
var form = ui.createForm({ title: "freemarker test" });
function getIssues() {
var issues = [];
return issues;
}
function formatIssues(issues) {
var html = [];
return html.join("\n");
}
var htmlField = form.addField({
id: "custpage_html",
label: "html",
type: ui.FieldType.INLINEHTML,
});
htmlField.defaultValue = formatIssues(getIssues());
context.response.writePage(form);
}
}
return {
onRequest: onRequest,
};
});
or, if you don't need any other NetSuite Form elements:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search"], function (search) {
function onRequest(context) {
if (context.request.method === "GET") {
function getIssues() {
var issues = [];
return issues;
}
function formatIssues(issues) {
var html = [];
return html.join("\n");
}
context.response.write(formatIssues(getIssues()));
}
}
return {
onRequest: onRequest,
};
});
You add the field to your form by calling Form.addField from your form object:
var field = html.addField({
id : 'custpage_inlineresults',
type : serverWidget.FieldType.INLINEHTML,
label : 'Search Results'
});
See SuiteAnswer #43669.

How to acess JSON object inside a script tag?

I have an API call to google directions API and then i
am trying to save that JSON response in a variable called as lat through this code
app.post("/from", function(req,res) {
from = req.body.from;
to = req.body.to;
const url = "https://maps.googleapis.com/maps/api/directions/json?origin="+ from + "&destination=" + to + "&key=AIzaSyDYRICW4Bm4donS0-9LCp_h0nlsyWvEuGY";
console.log(from,to);
https.get(url, function(response) {
console.log(response.statusCode);
var buffers = []
response
.on('data', function(data) {
buffers.push(data)
})
.on('end', function() {
lat = JSON.parse(Buffer.concat(buffers).toString());
console.log(lat);
Now, inside my ejs file i want to pass this response inside a script tag in order to render a map.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 12
});
var routes = directionsServiceResponse.routes;
console.log("legs " + routes[0].legs.length);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < routes[0].legs.length; i++) {
var leg = routes[0].legs[i];
for (var j = 0; j < leg.steps.length; j++) {
var step = leg.steps[j];
var color = "black";
if (step.travel_mode == "WALKING")
color = "red";
else if (step.travel_mode == "TRANSIT")
color = "green";
var polyline = new google.maps.Polyline({
path: google.maps.geometry.encoding.decodePath(step.polyline.points),
map: map,
strokeColor: color
});
google.maps.event.addListener(polyline, 'click', function(evt) {
infowindow.setContent("leg " + i + " polyline " + j)
})
for (var ii = 0; ii < polyline.getPath().getLength(); ii++) {
bounds.extend(polyline.getPath().getAt(ii));
}
}
}
map.fitBounds(bounds);
}
var directionsServiceResponse = <%= var %>
</script>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=key&callback=initMap&libraries=geometry" async defer></script>
i have tried passing that variable as a ejs variable but its not working

How do we get the Edit id of the corresponding node

I am trying to edit the GetOrgChart node by pointing it to a url which needs the id of the corresponding node to work. I am stuck here and would like the solution out. My code is as follows
getOrgChart.themes.monica.box += '<g transform="matrix(1,0,0,1,350,10)">'
+ btnAdd
+ btnEdit
+ btnDel
+ '</g>';
var orgChart = new getOrgChart(chartElement, {
scale: 0.5,
theme: "monica",
primaryFields: resp2.primaryFields,
photoFields: [resp2.photoField],
enableZoom: true,
enableEdit: true,
enableDetailsView: true,
dataSource: processed
});
function getNodeByClickedBtn(el) {
while (el.parentNode) {
el = el.parentNode;
if (el.getAttribute("data-node-id"))
return el;
}
return null;
}
var init = function () {
var btns = document.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function () {
var nodeElement = getNodeByClickedBtn(this);
var action = this.getAttribute("data-action");
var id = nodeElement.getAttribute("data-node-id");
var node = orgChart.nodes[id];
switch (action) {
case "add":
window.location.href='${request.contextPath}' + resp2.addLink;
break;
case "edit":
//console.log('&id=' + processed['id']);
// return;
window.location.href='${request.contextPath}' + resp2.editLink + '&id=' + resp.data[]['id'];
break;
case "delete":
window.location.href='${request.contextPath}' + resp2.deleteLink;
break;
}
});
}
}
init();
},
error: function (ex) {
console.log(ex);
}
});
},
error: function (ex) {
console.log(ex);
}
});
The problem code is here
case "edit":
//console.log('&id=' + processed['id']);
// return;
window.location.href='${request.contextPath}' + resp2.editLink + '&id=' + resp.data[]['id'];
break;
What should I do to access the id in the resp.data[index] variable?
I got my answer. The example extracted variables and id of the node was one of them.
var nodeElement = getNodeByClickedBtn(this);
var action = this.getAttribute("data-action");
var id = nodeElement.getAttribute("data-node-id");
var node = orgChart.nodes[id];

Touch event equivalent to mouse down

I'm trying to use a mouse:down event on canvas like:
canvas.on('mouse:down', function(options) {}
How can I use touchstart event handler?
I hope this helps
// TOUCH EVENTS
canvas.addEventListener("touchstart", function (e) {
e.preventDefault();
var mousePos = getTouchPos(canvas, e);
var touch = e.touches[0];
// do_mouse_click_logic(mousePos.x, mousePos.y, touch.clientX, touch.clientY);
}, false);
canvas.addEventListener("touchend", function (e) {
e.preventDefault();
var mousePos = getTouchPos(canvas, e);
// do_mouse_up_logic(mousePos.x, mousePos.y);
}, false);
canvas.addEventListener("touchmove", function (e) {
e.preventDefault();
var mousePos = getTouchPos(canvas, e);
var touch = e.touches[0];
// do_mouse_move_logic(mousePos.x, mousePos.y, touch.clientX, touch.clientY);
}, false);
function getTouchPos(canvasDom, touchEvent) {
var rect = canvasDom.getBoundingClientRect();
return {
x: touchEvent.touches[0].clientX - rect.left,
y: touchEvent.touches[0].clientY - rect.top
};
}
// MOUSE EVENTS
canvas.addEventListener('mousedown', function(evt) {
evt.preventDefault();
var mousepos = get_mouse_pos(canvas, evt);
// do_mouse_click_logic(mousepos.x, mousepos.y, evt.pageX, evt.pageY);
}, false);
canvas.addEventListener('mousemove', function(evt) {
evt.preventDefault();
var mousepos = get_mouse_pos(canvas, evt);
// do_mouse_move_logic(mousepos.x, mousepos.y, evt.pageX, evt.pageY);
});
canvas.addEventListener('mouseup', function(evt) {
evt.preventDefault();
var mousepos = get_mouse_pos(canvas, evt);
// do_mouse_up_logic(mousepos.x, mousepos.y);
}, false);
function get_mouse_pos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function do_mouse_click_logic(x, y, page_x, page_y) {
// Do your stuff
}
function do_mouse_move_logic(x, y, page_x, page_y) {
// Do your stuff
}
function do_mouse_up_logic(x, y) {
// Do yuor stuff
}

How to rotate sprite image in 360 degree view in fabric js

But the problem is iam not able to rotate the sprite image based on user interaction.for eg: when the user moves the mouse on right the frame on right side should moved and when the user moves on left the left side of the frames should me moved iam not able to implement this in fabric js. What i have done is just rotating the sprite image onmouse move.Expected output i want is like this :https://codyhouse.co/demo/360-degrees-product-viewer/index.html
var URL = 'https://codyhouse.co/demo/360-degrees-product-viewer/img/alfa.png';
var canvas = new fabric.Canvas('canvas');
var positions = {
topSteps: 1,
leftSteps: 16
};
var y = 0;
var x = 0;
var topStep;
var leftStep;
canWalk(URL, positions);
function canWalk(URL, positions) {
var myImage = new Image();
myImage.src = URL;
//var mDown = false;
//onloadevent
myImage.onload = function () {
topStep = myImage.naturalHeight / positions.topSteps;
leftStep = myImage.naturalWidth / positions.leftSteps;
var docCanvas = document.getElementById('canvas');
docCanvas.height = topStep;
docCanvas.width = leftStep;
fabricImageFromURL(x, y);
};
}
//mouseevents
canvas.on('mouse:out', function (event) {
console.log("mouseout")
/* x=0;
y=0;
fabricImageFromURL(x,y);*/
});
canvas.on('mouse:move', function (event) {
resetvalue();
setTimeout(function () {
console.log('value of x in start', x)
console.log('positions.leftSteps', positions.leftSteps)
if (x == positions.leftSteps) {
y = 1;
fabricImageFromURL(-y * topStep, -x * leftStep)
}
else {
fabricImageFromURL(-y * topStep, -x * leftStep)
if (x < positions.leftSteps) {
x++;
}
}
}, 50);
});
function resetvalue() {
if (x == positions.leftSteps) {
x = 0;
y = 0;
console.log("x and y value reset to0")
}
}
function fabricImageFromURL(top, left) {
console.log('fabricImageFromURL value', top, left);
fabric.Image.fromURL(URL, function (oImg) {
oImg.set('left', left).set('top', top);
oImg.hasControls = false;
oImg.hasBorders = false;
oImg.selectable = false;
canvas.add(oImg);
canvas.renderAll();
}, { "left": 0, "top": 0, "scaleX": 1, "scaleY": 1 });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.21/fabric.js"></script>
<canvas id="canvas"></canvas>
As we are not changing top value, no need to set top value all the time, just set left value for the image. pixelToSkip is the difference between mousemove pixel to call the function, if mouse move difference is less than that , then it wont call.
var URL = 'https://codyhouse.co/demo/360-degrees-product-viewer/img/alfa.png';
var canvas = new fabric.Canvas('canvas', {
selection: false
}),
imgObject;
var positions = {
topSteps: 1,
leftSteps: 16
};
var y = 0;
var x = 0;
var topStep;
var leftStep;
var isMouseDown = false;
var imgObject, pixelToSkip = 10;
var clickedPointer, currPointer, diff;
canWalk(URL, positions);
function canWalk(URL, positions) {
var myImage = new Image();
myImage.src = URL;
//var mDown = false;
//onloadevent
myImage.onload = function() {
topStep = myImage.naturalHeight / positions.topSteps;
leftStep = myImage.naturalWidth / positions.leftSteps;
canvas.setDimensions({
height : topStep,
width : leftStep
})
fabricImageFromURL(x, y);
};
}
//mouseevents
canvas.on('mouse:down', function(event) {
isMouseDown = true;
prevPointer = canvas.getPointer(event.e);
})
canvas.on('mouse:out', function(event) {
//console.log("mouseout")
/* x=0;
y=0;
fabricImageFromURL(x,y);*/
});
canvas.on('mouse:move', function(event) {
if (!isMouseDown) return;
currPointer = canvas.getPointer(event.e);
diff = currPointer.x - prevPointer.x;
if (diff < -pixelToSkip) {
if (x == positions.leftSteps) {
x = 0;
}
fabricImageFromURL(-x * leftStep)
x++;
prevPointer = currPointer;
} else if(diff > pixelToSkip){
if (x == 0) {
x = positions.leftSteps;
}
x--;
fabricImageFromURL(-x * leftStep)
prevPointer = currPointer;
}
});
canvas.on('mouse:up', function(event) {
isMouseDown = false;
})
function fabricImageFromURL(left) {
if (!imgObject) return
imgObject.set('left', left);
canvas.renderAll();
}
fabric.Image.fromURL(URL, function(oImg) {
imgObject = oImg;
oImg.set({
left: 0,
top: 0,
hasControls: false,
hasBorders: false,
selectable: false
});
canvas.add(oImg);
canvas.renderAll();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.21/fabric.js"></script>
<canvas id="canvas"></canvas>

Resources