How to properly use hideDayPicker() public function from react-day-picker-input? - hide

I'm trying to hide my calendar by clicking the react-day-picker-input element again (it will open when you click it by default). For that, I have a state that records true or false when you click the element. The problem is that when I click again to hide it, it gives me the error below:
TypeError: calendarNode.hideDayPicker is not a function
I tried using showOverlay and hideDayPicker.
I saw a code that works with buttons, but fails to achieve the results when you apply onClick to the DayPickerInput component (see below).
https://codesandbox.io/s/oqm3p4j9rz
Here's my code (summarized):
onKeyPress = (event) => {
event.preventDefault();
}
dateRestriction = () => {
const date = new Date();
const nutrition_offset = date.getTimezoneOffset() + 240;
date.setMinutes(date.getMinutes() + nutrition_offset);
const year = date.getFullYear();
const month = date.getMonth() + 1;
let day = date.getDate();
if ((date.getDay() === 4) || (date.getDay() === 5)) {
if (date.getDate() < 5) {
day = ('0' + (date.getDate() + 5));
} else {
day = date.getDate() + 5;
}
}
if (date.getDay() === 6) {
if (date.getDate() < 6) {
day = ('0' + (date.getDate() + 4));
} else {
day = date.getDate() + 4;
}
}
if ((date.getDay() === 0) || (date.getDay() === 1) || (date.getDay() === 2) || (date.getDay() === 3)) {
if (date.getDate() < 7) {
day = ('0' + (date.getDate() + 3));
} else {
day = date.getDate() + 3;
}
}
let dateRestricted = this.parseDate_(year + '-' + month + '-' + day);
this.setState({
noDay: dateRestricted,
showCalendar: true
});
this.handleDayPickerInputHide();
}
handleDayPickerInputHide = () => {
const calendarNode = document.getElementsByName("date");
if (this.state.showCalendar === false) {
return;
} else {
calendarNode.hideDayPicker();
this.setState = {
showCalendar: false
}
}
}
render () {
const { selectedDay } = this.state;
return (
<div>
<DateObject
inputProps={
{className: 'dib nav pl2 pointer br3 shadow-1 dropdownButtonDate removeCursor bg-transparent pv1 mt2 typefaceFont dropdownText',
onKeyDown: this.onKeyPress,
onClick: this.dateRestriction,
name: 'date',
required: "required"}
}
value={selectedDay}
onDayChange={this.handleDayChange}
dayPickerProps={{
selectedDays: selectedDay,
disabledDays:
[
new Date(2019, 0, 1),
new Date(2019, 11, 24),
new Date(2019, 11, 25),
new Date(2019, 11, 31),
{
daysOfWeek: [0, 6],
},
{
before: new Date(this.state.noDay)
}]
}}
/>
</div>
)
}
Expected:
1. Calendar is hidden initially (default behavior)
2. Click displays calendar (default behavior)
3. Click again to hide the calendar (NEEDED)
4. Click outside hides the calendar as well (default behavior)
5. Choose a date hides the calendar as well (default behavior)
Actual results:
1. Calendar is hidden initially (default behavior)
2. Click displays calendar (default behavior)
3. Click again to hide the calendar (ERROR)
4. Click outside hides the calendar as well (default behavior)
5. Choose a date hides the calendar as well (default behavior)

FIGURED IT OUT!!!
There's no need to update the state, use DOM or attempt to run a public function from your react-app. All you need to do is update react-day-picker from your node_modules.
Man... This needs to go with their next version of react-day-picker...
Check it out!
{
key: 'handleInputClick',
value: function handleInputClick(e) {
//this.showDayPicker();
if (this.props.inputProps.onClick) {
e.persist();
this.props.inputProps.onClick(e);
if (this.state.showOverlay === false) {
this.showDayPicker();
}
if (this.state.showOverlay === true) {
this.hideDayPicker();
}
}
}
}, {
key: 'handleInputFocus',
value: function handleInputFocus(e) {
var _this5 = this;
//this.showDayPicker();
// Set `overlayHasFocus` after a timeout so the overlay can be hidden when
// the input is blurred
this.inputFocusTimeout = setTimeout(function () {
_this5.overlayHasFocus = false;
}, 2);
if (this.props.inputProps.onFocus) {
e.persist();
this.props.inputProps.onFocus(e);
}
}
Navigate to your node_modules directory and find DayPickerInput.js within ../node_modules/react-day-picker/lib/src/DayPickerInput.js
Comment out (or remove) this.showDayPicker() under 'handleInputFocus' and 'handleInputClick'.
Added the conditional below this.props.inputProps.onClick(e) (line 349)
Note: There's no need to update showOverlay, as hideDayPicker() and showDayPicker() already do that.

Related

Trying to copy the text of a web page into Excel

I am using this code to open Edge so that I can grab the text of the web page. I can get Edge to open and display the page, and I can copy the text of the page manually and then finish executing the code and it pastes it as needed, but I'm not at the skill level to figure out how to make Excel copy the text. It's the last step that I need.
Any help would be greatly appreciated.
I'm looking to copy the entire page, and not just one section of it.
Sub LOADEdge()
Set obj = CreateObject("Shell.Application")
obj.ShellExecute "microsoft-edge:https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+HOllywood&key=your_API_Key"
'This is where I manually grab the text from the page.
MsgBox "wiating"
Worksheets("sheet1").Range("A1").PasteSpecial Page = xlpagevalues
End Sub
I've tried to research how to copy web pages but most require Selenium to be installed and I can't get my IT department to do that for me. I've found work arounds on how to open the browser but I can't find anything that shows me how to copy the text of the page other than:
IE.ExecWB 17, 0 '// SelectAll
IE.ExecWB 12, 2 '// Copy selection
but that doesn't work.
While it is possible, I am not sure that VBA is a good tool for web scraping. I tried it a few times, and it never gave me the results I was looking for. Here are some alternatives to look at:
Using Google Sheets
Using Python
There is also an add-in for Microsoft One-Note that lets you save the entire content of a webpage to OneNote, and it works quite well.
It is node.js with exceljs and axios library.
This code will write excel file.
It needs to paste your 'API_KEY' string at line 4.
Save as get-map.js
const axios = require('axios')
const Excel = require('exceljs');
const API_KEY ='your_API_Key'
const columnName = (index) => {
var cname = String.fromCharCode(65 + ((index - 1) % 26))
if (index > 26)
cname = String.fromCharCode(64 + (index - 1) / 26) + cname
return cname;
}
const getMapInformation = async (origin, destination) => {
try {
origin = origin.replace(/ /g,"+") // replace from space to '+'
destination = destination.replace(/ /g,"+") // replace from space to '+'
const resp = await axios.get(
`https://maps.googleapis.com/maps/api/directions/json?origin=${origin}&destination=${destination}&key=${API_KEY}`
);
return Promise.resolve(resp.data);
} catch (err) {
return Promise.reject(error);
}
}
const writeMapInformation = (fileName, data) => {
try {
const workbook = new Excel.Workbook();
// make workbook with 'map' name
const ws = workbook.addWorksheet("map")
// Start Cell A1 for title column
let headerColumn = 1
let row_number = 1
// #1 geocoded_waypoints section
for (let waypoint in data.geocoded_waypoints) {
for (let key in data.geocoded_waypoints[waypoint]) {
ws.getCell(columnName(headerColumn) + String(row_number)).value = key
ws.getCell(columnName(headerColumn + 1) + String(row_number)).value = data.geocoded_waypoints[waypoint][key]
row_number++;
}
row_number++; // skip one row
}
// #2 routes section
for (let index in data.routes) {
for (let key in data.routes[index]) {
if(key == 'bounds') {
ws.getCell(columnName(headerColumn) + String(row_number)).value = key
for (let sub_key in data.routes[index][key]) {
ws.getCell(columnName(headerColumn + 1) + String(row_number)).value = sub_key
ws.getCell(columnName(headerColumn + 2) + String(row_number)).value = data.routes[index][key][sub_key]
row_number++;
}
}
if(key == 'summary') {
ws.getCell(columnName(headerColumn) + String(row_number)).value = key
ws.getCell(columnName(headerColumn + 1) + String(row_number)).value = data.routes[index][key]
}
if(key == 'legs') {
ws.getCell(columnName(headerColumn) + String(row_number)).value = key
row_number++;
for (let sub_key in data.routes[index][key][0]) {
if(sub_key != 'steps') {
ws.getCell(columnName(headerColumn + 1) + String(row_number)).value = sub_key
ws.getCell(columnName(headerColumn + 2) + String(row_number)).value = data.routes[index][key][0][sub_key]
row_number++;
}
if(sub_key == 'steps') {
for (let sub_child_key in data.routes[index][key][0][sub_key]) {
for (let grand_key in data.routes[index][key][0][sub_key][sub_child_key]) {
// skip two fileds (html_instructions & polyline)
if(grand_key != 'html_instructions' && grand_key != 'polyline') {
ws.getCell(columnName(headerColumn + 1) + String(row_number)).value = grand_key
ws.getCell(columnName(headerColumn + 2) + String(row_number)).value = data.routes[index][key][0][sub_key][sub_child_key][grand_key]
row_number++;
}
}
}
}
}
row_number++;
}
}
}
workbook.xlsx
.writeFile(fileName)
.then(() => {
console.log('file created');
})
.catch(err => {
console.log(err.message);
});
} catch (err) {
console.log(err.message);
}
}
// get map direction (from, to)
getMapInformation('Disneyland', 'Universal Studios Hollywood')
.then((result) => {
writeMapInformation('map.xlsx', result)
})
Install libraries
npm install axios exceljs
Run it
node get-map.js
Results

How do you write SharePoint 2010 conditional formatting for this?

I am using SPD 2010 and SharePoint Sever 2010.
Using conditional formatting I'm trying to format a list so that if today's date is greater than 30 days before the start date column a cell will turn red.
I've tried several XPath expressions from other Stackoverflow entries but nothing has worked. I'm wondering if I am even adding the XPath expression in the right place: In SPD I am selecting a date from the desired column, choosing "Conditional Formatting", selecting "Format Column", selecting "Advanced" and putting my expressions in the XPath expression textbox.
Appreciate your help!
I'm going to suggest a non-Xpath approach, but if you're looking to stick with Xpath you should take a look at the answers on this similar question.
After struggling with this problem myself, I've taken to using JavaScript for conditional formatting, since it can work with dates (including the current date), numbers, and strings, and it can manipulate HTML pretty easily.
A bit of client side code can automatically:
Detect whether a list of conditional formatting rules exists
Create the list if necessary
Provide an interface for creating new rules (which are stored as list items) that should apply to the current page
Loop through all the current page's rules and apply them to any list view web parts detected on the same page
The nicest part of this approach is that I can add the web part to a page and just let the business users configure the formatting to their liking; no need for me to be further involved whenever they want to change something.
I put the combined HTML/CSS/JavaScript in a text file that can be saved to a document library somewhere in my site collection. To then add the conditional formatting to page, I just add a content editor web part to the page and set its "content link" property to be the path to the text file.
The content editor web part then displays a gray "Conditional Formatting" button that the user can click to view and modify the formatting rules, as seen in the screen shot below.
Here's the conditional formatting code for SharePoint 2010 that I use in my text file:
<div id="_conditional_formatting_link" style="display:none; ">
<div unselectable="on" style="display:inline-block; user-select:none; cursor:pointer; padding: 3px; background-color:#9b9b9b; color:white; border:1px solid #888;" onclick="javascript:var rules = document.getElementById('_conditional_formatting'); if(rules.style.display == 'none'){rules.style.display = 'inline-block'}else{rules.style.display = 'none'}">
Conditional Formatting
</div>
</div>
<div id="_conditional_formatting" style="display:none;background-color:#dfdfdf; border: 1px solid black; width:95%; max-width:1100px;">
<a style="border:0px;padding:5px;float:right;" title="Reapply Formatting" href="javascript:getConditions(false);">
<img style="border:0px;" src="/_layouts/images/staticrefresh.gif"/>
</a>
<ol id="_conditional_formatting_rules"></ol>
<div style="text-align:right; ">
<div id="_add_conditional_formatting_rule" unselectable="on" onclick="javascript: Add_Conditional_Formatting();" style="user-select:none; cursor:pointer; padding: 3px; margin: 3px; display:inline-block; background-color:#9b9b9b; border:1px solid #888; color:white;">Add Rule</div>
</div>
</div>
<script>
this.cfl = this.cfl ? this.cfl : new Object(null);
var conditionalFormattingList = "Conditional Formatting";
function getConditions(reloadRules) {
/* if reloadRules, query the conditions list and get all the rules. Otherwise just reapply the ones in memory to the current document. */
if (typeof reloadRules == "undefined") { reloadRules = true; }
if (reloadRules) {
var conditionalFormattingRules = document.getElementById("_conditional_formatting_rules");
while (conditionalFormattingRules.children.length > 0) { /* Clear out the currently displayed list of rules. */
conditionalFormattingRules.removeChild(conditionalFormattingRules.children[0]);
}
this.cfl.clientContext = new SP.ClientContext();
this.cfl.user = cfl.clientContext.get_web().get_currentUser();
var list = cfl.clientContext.get_web().get_lists().getByTitle(conditionalFormattingList);
var camlQuery = new SP.CamlQuery();
var folder = list.get_rootFolder();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'URL\' /><Value Type=\'Text\'>' + document.location.pathname + '</Value></Eq></Where><OrderBy><FieldRef Name=\'Priority\' /><FieldRef Name=\'Name\' /></OrderBy></Query></View>');
this.cfl.items = list.getItems(camlQuery);
cfl.clientContext.load(cfl.user);
cfl.clientContext.load(list, 'EffectiveBasePermissions');
cfl.clientContext.load(cfl.items);
cfl.clientContext.load(folder);
}
this.cfl.clientContext.executeQueryAsync(
Function.createDelegate(this,
function () {
var Me = this.cfl.user.get_title();
if (reloadRules) {
var baseFormUrl = folder.get_serverRelativeUrl() + "/EditForm.aspx?ID=";
/* Figure out if the current user has access to create or edit items on the Conditional Formatting list */
var perms = list.get_effectiveBasePermissions();
this.cfl.hasEdit = perms.has(SP.PermissionKind.editListItems);
this.cfl.hasCreate = perms.has(SP.PermissionKind.addListItems);
/* Fill an array with our formatting rules */
this.cfl.targets = [];
var itemEnumerator = this.cfl.items.getEnumerator();
while (itemEnumerator.moveNext()) {
var item = itemEnumerator.get_current();
var targ = new Object(null);
targ.column = item.get_item("Column");
targ.comparison = item.get_item("Comparison");
targ.style = item.get_item("Style");
targ.scope = item.get_item("Scope");
targ.type = item.get_item("Type");
targ.value = item.get_item("Value"); if (targ.value == null) { targ.value = ""; }
targ.id = item.get_item("ID");
targ.offset = item.get_item("Offset");
cfl.targets.push(targ);
}
}
if (!this.cfl.hasCreate) { document.getElementById("_add_conditional_formatting_rule").style.display = "none"; }
for (var targetIterator = 0, len = cfl.targets.length; targetIterator < len; targetIterator++) {
var currentTarget = cfl.targets[targetIterator];
if (reloadRules) {
var rulelist = document.getElementById("_conditional_formatting_rules");
var ruletoadd = document.createElement("li");
var comparisondisplay = currentTarget.type.indexOf("Field") != -1 ? "value of the <b>" + currentTarget.value + "</b> column" : "<b>'" + currentTarget.value + "'</b>";
if (currentTarget.type == "Special" || currentTarget.type == "Number") {
if (currentTarget.value.toString().toLowerCase() == "[me]") { comparisondisplay = "<b>[Me](" + Me + ")</b>"; }
else { comparisondisplay = "<b>" + currentTarget.value + "</b>"; }
}
if (currentTarget.value == "") { comparisondisplay = "<b>(blank)</b>"; }
if (currentTarget.offset != null) {
comparisondisplay += "<b>" + (currentTarget.offset < 0 ? " " : " +") + currentTarget.offset + "</b>"
}
var editLink = this.cfl.hasEdit ? "<div style='display:inline-block;cursor:pointer;' onclick='SP.UI.ModalDialog.commonModalDialogOpen(" + '"' + baseFormUrl + currentTarget.id + '&Source=' + document.location.pathname + '"' + ",{},refreshPageConditions); '>" + "<img src='/_layouts/images/EDITITEM.GIF' style='vertical-align:middle;' title='Customize' alt='Customize'/>" + " </div>" : "";
ruletoadd.innerHTML = editLink + "When <b>" + currentTarget.column + "</b> "
+ currentTarget.comparison + " " + comparisondisplay
+ ", apply {" + (currentTarget.style == null ? "remove all formatting" : "<span style='" + currentTarget.style + "'>" + currentTarget.style + "</span>") + "} to the <b>" + currentTarget.scope + "</b>" + ((currentTarget.scope != "Cell" && currentTarget.scope != "Row") ? " column" : "");
rulelist.appendChild(ruletoadd);
}
var tables = document.querySelectorAll("table.ms-listviewtable"); /* Should get all the list view web parts on the page. */
var t_i = 0;
while (t_i < tables.length) {
var columnIndex = null; /* Index of the column to compare against */
var valueIndex = null; /* Index of a second column from which to pull the value to compare */
var styleTargetIndex = null; /* Index of a column to apply formatting to */
var thisTable = tables[t_i];
var headings = thisTable.rows[0].cells;
var h_i = 0;
while (h_i < headings.length) { /* Check all the column headings... */
var thisHeading = headings[h_i].querySelector("div:first-child");
if (thisHeading != null) {
/* In Internet Explorer, the headings have a DisplayName attribute you can grab. If that's not there, just grab the innerText or textContent */
var dispname = thisHeading.DisplayName ? thisHeading.DisplayName : (thisHeading.innerText ? thisHeading.innerText : thisHeading.textContent);
dispname = dispname.replace(/^\s+|\s+$/g, '');/* removes leading and trailing whitespace */
if (currentTarget.scope != "Cell" && currentTarget.scope != "Row") {
/*If the scope isn't Cell or Row, see if this is the cell to which the formatting should applied */
if (dispname == currentTarget.scope) { styleTargetIndex = h_i; }
}
if (currentTarget.type.indexOf("Field") != -1) {
/*If the value type is a Field, check to see if this is the field whose value we care about */
if (dispname == currentTarget.value.toString()) { valueIndex = h_i; }
}
if (dispname == currentTarget.column) { columnIndex = h_i; }
}
h_i += 1;
}
if (columnIndex != null) { /* If we found a matching heading, let's try to apply the rules... */
var rows = thisTable.rows;
for (var i = (rows.length > 0 ? 1 : 0) ; i < rows.length; i++) {
var cells = rows[i].children;
if (cells.length <= columnIndex) { continue }
var innerLink = cells[columnIndex].querySelector("a"); /* I want to specifically target links so that we can change their text color if necessary */
/* Populate valueToEval with the text value of the current cell, or its inner link if it has one */
var valueToEval = cells[columnIndex].innerText ? (innerLink != null ? innerLink.innerText : cells[columnIndex].innerText) : (innerLink != null ? innerLink.textContent : cells[columnIndex].textContent);
if (typeof (valueToEval) == "undefined") { valueToEval = "" } /* Treat empties as blanks */
var listValueToCompareAgainst = null;
if (valueIndex != null) { /* valueIndex only has a value if we need to grab the comparison value from another column on the list */
valueLink = cells[valueIndex].querySelector("a");
listValueToCompareAgainst = cells[valueIndex].innerText ? (valueLink != null ? valueLink.innerText : cells[valueIndex].innerText) : (valueLink != null ? valueLink.textContent : cells[valueIndex].textContent);
}
var needsStyling = false;
switch (currentTarget.type) {
case "Number":
if (!isNaN(Number(valueToEval))) {
valueToEval = +(valueToEval);
}
if (!isNaN(Number(currentTarget.value))) {
currentTarget.value = +(currentTarget.value);
}
break;
case "Date":
valueToEval = new Date(valueToEval);
currentTarget.value = new Date(currentTarget.value);
if (currentTarget.offset != null) {
currentTarget.value.setDate(currentTarget.value.getDate() + +(currentTarget.offset));
}
break;
case "Text": /* Already covered, bro */ break;
case "Date Field":
valueToEval = new Date(valueToEval);
currentTarget.value = new Date(listValueToCompareAgainst);
if (currentTarget.offset != null) {
currentTarget.value.setDate(currentTarget.value.getDate() + +(currentTarget.offset));
}
break;
case "Text Field": currentTarget.value = listValueToCompareAgainst; break;
case "Number Field":
if (!isNaN(Number(listValueToCompareAgainst))) {
currentTarget.value = listValueToCompareAgainst;
if (currentTarget.offset != null) {
currentTarget.value += Number(currentTarget.offset);
}
}
if (!isNaN(Number(valueToEval))) {
valueToEval = Number(valueToEval);
}
break;
case "Special":
if (currentTarget.value.toLowerCase) {
if (currentTarget.value.toLowerCase() == "[me]") { currentTarget.value = Me }
else if (currentTarget.value.toLowerCase().indexOf("[today]") != -1) {
var dateDifference = Number(currentTarget.value.toLowerCase().replace("[today]", "").replace(" ", "").replace("+", ""));
currentTarget.value = new Date();
if (!isNaN(dateDifference)) { currentTarget.value.setDate(currentTarget.value.getDate() + dateDifference); }
if (currentTarget.offset != null) {
currentTarget.value.setDate(currentTarget.value.getDate() + Number(currentTarget.offset));
}
valueToEval = new Date(valueToEval);
}
} else { valueToEval = new Date(valueToEval); }
break;
}
switch (currentTarget.comparison) {
case "Greater Than or Equal To": needsStyling = (valueToEval >= currentTarget.value); break;
case "Greater Than": needsStyling = (valueToEval > currentTarget.value); break;
case "Less Than or Equal To": needsStyling = (valueToEval <= currentTarget.value); break;
case "Less Than": needsStyling = (valueToEval < currentTarget.value); break;
case "Equal To": needsStyling = (valueToEval == currentTarget.value); break;
case "Not Equal To": needsStyling = (valueToEval != currentTarget.value); break;
case "Contains": needsStyling = (valueToEval.indexOf(currentTarget.value) != -1); break;
case "Does Not Contain": needsStyling = (valueToEval.indexOf(currentTarget.value) == -1); break;
}
if (needsStyling) {
var links;
if (currentTarget.scope != "Row") {
var targetIndex = (styleTargetIndex != null) ? styleTargetIndex : columnIndex;
cells[targetIndex].setAttribute("style", currentTarget.style);
links = cells[targetIndex].querySelectorAll("a");
} else {
rows[i].setAttribute("style", currentTarget.style);
for (var j = 0; j < cells.length; j++) {
cells[j].setAttribute("style", currentTarget.style);
}
links = rows[i].querySelectorAll("a");
}
for (var j = 0; j < links.length; j++) {
if (links[j].title != "Open Menu") {
links[j].setAttribute("style", currentTarget.style);
links[j].style.backgroundColor = "";
}
links[j].style.border = "0px";
}
}
}
}
t_i += 1;
}
}
document.getElementById("_conditional_formatting_link").style.display = "inline-block";
}
),
Function.createDelegate(this,
function (sender, args) { /* There was an error accessing the list. Time to create it! */
var lci = new SP.ListCreationInformation();
lci.set_title(conditionalFormattingList);
lci.set_templateType(SP.ListTemplateType.genericList);
var condition_list = clientContext.get_web().get_lists().add(lci);
clientContext.load(condition_list);
var colTitle = condition_list.get_fields().getByTitle("Title");
colTitle.set_required(false); colTitle.set_hidden(true); colTitle.update();
condition_list.update();
var colColumn = condition_list.get_fields().addFieldAsXml('<Field Description=\'The column to compare (must be visible on the page)\' DisplayName=\'Column\' Type=\'Text\'/>', true, SP.AddFieldOptions.defaultValue);
var colComparison = condition_list.get_fields().addFieldAsXml('<Field Description=\'\' Type=\'Choice\' DisplayName=\'Comparison\' Format=\'Dropdown\' FillInChoice=\'FALSE\'><Default>Equal To</Default><CHOICES><CHOICE>Greater Than</CHOICE><CHOICE>Greater Than or Equal To</CHOICE><CHOICE>Equal To</CHOICE><CHOICE>Less Than or Equal To</CHOICE><CHOICE>Less Than</CHOICE><CHOICE>Not Equal To</CHOICE><CHOICE>Contains</CHOICE><CHOICE>Does Not Contain</CHOICE></CHOICES></Field>', true, SP.AddFieldOptions.defaultValue);
var colValue = condition_list.get_fields().addFieldAsXml('<Field Description=\'The value or the name of a column to compare against\' DisplayName=\'Value\' Type=\'Text\'/>', true, SP.AddFieldOptions.defaultValue);
var colType = condition_list.get_fields().addFieldAsXml('<Field Description=\'Indicate the type of value you are comparing against. Choose Special if using the [Me] or [Today] placeholders.\' Type=\'Choice\' DisplayName=\'Type\' Format=\'Dropdown\' FillInChoice=\'FALSE\'><Default>Text</Default><CHOICES><CHOICE>Date</CHOICE><CHOICE>Number</CHOICE><CHOICE>Text</CHOICE><CHOICE>Date Field</CHOICE><CHOICE>Number Field</CHOICE><CHOICE>Text Field</CHOICE><CHOICE>Special</CHOICE></CHOICES></Field>');
var colOffset = condition_list.get_fields().addFieldAsXml('<Field Description=\'Optionally specify a number to offset the value by when comparing against a number or date.\' DisplayName=\'Offset\' Type=\'Number\' />', true, SP.AddFieldOptions.defaultValue);
var colStyle = condition_list.get_fields().addFieldAsXml('<Field NumLines=\'4\' Description=\'The CSS to apply to when the condition is met. Leave blank to remove formatting. Example syntax: background-color:darkred; color:white; font-weight:bold;\' DisplayName=\'Style\' Type=\'Note\' />', true, SP.AddFieldOptions.defaultValue);
var colScope = condition_list.get_fields().addFieldAsXml('<Field Description=\'The scope to which the style should be applied. Choose Row, Cell, or specify a column name.\' Type=\'Choice\' DisplayName=\'Scope\' Format=\'Dropdown\' FillInChoice=\'TRUE\'><Default>Cell</Default><CHOICES><CHOICE>Cell</CHOICE><CHOICE>Row</CHOICE></CHOICES></Field>', true, SP.AddFieldOptions.defaultValue);
var colPriority = condition_list.get_fields().addFieldAsXml('<Field Description=\'Priority determines which styles are applied in case of overlapping conditions. Higher numbers are applied later.\' DisplayName=\'Priority\' Type=\'Number\' />', true, SP.AddFieldOptions.defaultValue);
var colUrl = condition_list.get_fields().addFieldAsXml('<Field Description=\'Page where this rule should be applied\' DisplayName=\'URL\' Type=\'Text\'/>', true, SP.AddFieldOptions.defaultValue);
clientContext.executeQueryAsync(
Function.createDelegate(this, function () { getConditions(); }),
Function.createDelegate(this, function (sender, args) { document.getElementById("_conditional_formatting").innerHTML = ("An error occcurred while trying to apply conditional formatting to the list for you. Error details: " + args.get_message() + " " + args.get_stackTrace()); document.getElementById("_conditional_formatting_link").style.display = "inline-block"; }));
}
));
}
/* This method is called when the Add Rule button is clicked. */
function Add_Conditional_Formatting() {
/* Create a new item with only the URL and Priority fields filled out */
var currUrl = document.location.pathname;
var clientContext = new SP.ClientContext();
var itemCreateInfo = new SP.ListItemCreationInformation();
var newItem = clientContext.get_web().get_lists().getByTitle(conditionalFormattingList).addItem(itemCreateInfo);
newItem.set_item('URL', currUrl);
/* Give the new item a priority that will put it at the end of the list. This is kind of a hack since the highest priority is not necessarily the rulecount. */
newItem.set_item('Priority', document.getElementById("_conditional_formatting_rules").children.length + 1);
newItem.update();
clientContext.load(newItem);
clientContext.executeQueryAsync(Function.createDelegate(this, function () {
getConditions(); /* Reload to refresh the rules list after adding the item */
}), Function.createDelegate(this, function (sender, args) { alert(args.get_message()); }));
}
/* This method is called when the Edit Item dialog box is closed. It refreshes the page it the item was saved. */
function refreshPageConditions(result) { if (result != SP.UI.DialogResult.cancel) { window.location.replace(document.location.href) } }
ExecuteOrDelayUntilScriptLoaded(function () {
getConditions();
/* If there are any collapsible sections on the page, keep checking to see whether formatting needs to be reapplied */
this.cfl.TableRowCount = 0;
if (document.querySelector("img[alt='expand']") != null) {
setInterval(function () {
var tempTableRowCount = document.querySelectorAll("tr").length;
if (tempTableRowCount != this.cfl.TableRowCount) {
/* Only reapply formatting if the count of table rows is different than it was previously */
this.cfl.TableRowCount = tempTableRowCount;
getConditions(false) /* Passing false reapplies loaded rules without re-querying the SharePoint list */
}
}, 1000)
}
}, "SP.JS");
</script>

how to turn off sliding responsive menu in wordpress responsive select menu plugin?

I am using WP Responsive Select Menu plugin in wordpress and I have responsive menu while watching the website in the mobile devices.
In my IOS based phone, the responsive menu opens automatically when I scroll the screen to left (and sometimes also when I scroll down).
My .js file is as follows:
`
// Start Code
jQuery(document).ready(function( $ ) {
var bar = $('#wpresmenu_bar'), //top bar that shows/hides the menu
bar_height = bar.outerHeight(true), //the bar height
from_width = wpresmenu.from_width,
menu = $('#wpresmenu_menu'), //the menu div
menu_ul = $('#wpresmenu_menu_ul'), //the menu ul
menu_a = menu.find('a'), //single menu link
body = $('body'),
html = $('html'),
animation_speed = 300,
ab = $('#wpadminbar'),
menu_enabled = (bar.length > 0 && menu.length > 0)? true : false,
menu_width = menu.width(),
target_height = (window.innerHeight < body.height())? body.height() : window.innerHeight,
target_width = (window.innerWidth < body.width())? body.width() : window.innerWidth;
if(menu_enabled) {
menu_ul.find('li').first().css({'border-top':'none'});
$(document).mouseup(function (e) {
if ( !menu.is(e.target) && menu.has( e.target ).length === 0) {
if(menu.is(':visible') && (!menu.hasClass('top'))) {
$.sidr('close', 'wpresmenu_menu');
}
}
});
//ENABLE NESTING
//add arrow element to the parent li items and chide its child uls
menu.find('ul.sub-menu').each(function() {
var sub_ul = $(this),
parent_a = sub_ul.prev('a'),
parent_li = parent_a.parent('li').first();
parent_a.addClass('wpresmenu_parent_item');
parent_li.addClass('wpresmenu_parent_item_li');
var expand = parent_a.before('<span class="wpresmenu_icon wpresmenu_icon_par icon_default"></span> ').find('.wpresmenu_icon_par');
sub_ul.hide();
});
//adjust the a width on parent uls so it fits nicely with th eicon elemnt
function adjust_expandable_items() {
$('.wpresmenu_parent_item_li').each(function() {
var t = $(this),
main_ul_width = 0,
icon = t.find('.wpresmenu_icon_par').first(),
link = t.find('a.wpresmenu_parent_item').first();
if(menu.hasClass('top')) {
main_ul_width = window.innerWidth;
} else {
main_ul_width = menu_ul.innerWidth();
}
if(t.find('.wpresmenu_clear').length == 0) link.after('<br class="wpresmenu_clear"/>');
});
}
adjust_expandable_items();
//expand / collapse action (SUBLEVELS)
$('.wpresmenu_icon_par').on('click',function() {
var t = $(this),
//child_ul = t.next('a').next('ul');
child_ul = t.parent('li').find('ul.sub-menu').first();
child_ul.slideToggle(300);
t.toggleClass('wpresmenu_par_opened');
t.parent('li').first().toggleClass('wpresmenu_no_border_bottom');
});
//helper - close all submenus when menu is hiding
function close_sub_uls() {
menu.find('ul.sub-menu').each(function() {
var ul = $(this),
icon = ul.parent('li').find('.wpresmenu_icon_par'),
li = ul.parent('li');
if(ul.is(':visible')) ul.slideUp(300);
icon.removeClass('wpresmenu_par_opened');
li.removeClass('wpresmenu_no_border_bottom');
});
}
//fix the scaling issue by adding/replacing viewport metatag
var mt = $('meta[name=viewport]');
mt = mt.length ? mt : $('<meta name="viewport" />').appendTo('head');
if(wpresmenu.zooming == 'no') {
mt.attr('content', 'user-scalable=no, width=device-width, maximum-scale=1, minimum-scale=1');
} else {
mt.attr('content', 'user-scalable=yes, width=device-width, initial-scale=1.0, minimum-scale=1');
}
//Additional fixes on change device orientation
if( $.browser.mozilla ) {
screen.addEventListener("orientationchange", function() {updateOrientation()}); //firefox
} else if( window.addEventListener ) {
window.addEventListener('orientationchange', updateOrientation, false);
}
else {
window.attachEvent( "orientationchange" );
}
function updateOrientation() {
window.scrollBy(1,1);
window.scrollBy(-1,-1);
menu_width = menu.width();
//update the page posion for left menu
if(menu.is(':visible') && menu.hasClass('left')) {
body.css({'left':menu_width});
body.scrollLeft(0);
}
}
//apply the SIDR for the left/right menu
if(menu.hasClass('left') || menu.hasClass('right')) {
//appy sidr
var hor_pos = (menu.hasClass('left'))? 'left' : 'right';
bar.sidr({
name:'wpresmenu_menu',
side: hor_pos,
speed: animation_speed,
onOpen: function(){ bar.addClass('menu_is_opened'); },
onClose: function(){ bar.removeClass('menu_is_opened'); close_sub_uls(); }
});
//when link is clicked - hide the menu first and then change location to new page
menu_a.on('click', function(e) {
$.sidr('close', 'wpresmenu_menu');
});
if( wpresmenu.swipe != 'no' ) {
$('body').touchwipe({
wipeLeft: function() {
// Close
$.sidr('close', 'wpresmenu_menu');
},
wipeRight: function() {
// Open
$.sidr('open', 'wpresmenu_menu');
},
min_move_x: 60,
min_move_y: 60,
preventDefaultEvents: false
});
}
$(window).resize(function(){
target_width = (window.innerWidth < body.width())? body.width() : window.innerWidth;
if(target_width > from_width && menu.is(':visible')) {
$.sidr('close', 'wpresmenu_menu');
}
});
} else if(menu.hasClass('top')) { //The top positioned menu
body.prepend(menu);
//show / hide the menu
bar.on('click', function(e) {
//scroll window top
$("html, body").animate({ scrollTop: 0 }, animation_speed);
close_sub_uls();
menu.stop(true, false).slideToggle(animation_speed);
});
//when link is clicked - hide the menu first and then change location to new page
menu_a.on('click', function(e) {
e.preventDefault();
var url = $(this).attr('href');
menu.slideUp(animation_speed,function() {
//go to the url from the link
window.location.href = url;
});
});
$(window).resize(function(){
target_width = (window.innerWidth < body.width())? body.width() : window.innerWidth;
if(target_width > from_width && menu.is(':visible')) {
close_sub_uls();
menu.slideUp(animation_speed, function() {});
}
});
} //end if class left / top /right
} //end if menu enabled
}); `
I don't want the menu to load on sliding the screen to left or right. Any idea how to do that??
I have figured it out.
Commenting out the following code stops it.
if( wpresmenu.swipe != 'no' ) {
$('body').touchwipe({
wipeLeft: function() {
// Close
$.sidr('close', 'wpresmenu_menu');
},
wipeRight: function() {
// Open
$.sidr('open', 'wpresmenu_menu');
},
min_move_x: 60,
min_move_y: 60,
preventDefaultEvents: false
});
}
:)

How to change a color of one particular bar using jqplot and stacked bar chart

I got one straight forward question. Is it possible to change the color of one bar in stacked bar chart in any way (using jqplot options or relying on a hack)?
I have this:
I want this:
So as you can already assume I am using 3 different colors for the stacked bar chart:
seriesColors: ['#afafaf', '#c4c6c4', '#dbdcdd']
Problem is that I want to add one specific color for 1 particular bar.
Here is the JS code:
$(document).ready(
function() {
var el = [ 3, 6, 0, 10, 12 ];
var ael = [ 14, 5, 0, 4, 2 ];
var ipv = [ 4, 9, 0, 8, 4 ];
var months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May' ];
var colors = ['blue', 'red', 'white'];
plot3 = $.jqplot('elDiagram', [ el, ael, ipv ], {
stackSeries : true,
seriesColors: colors,
captureRightClick : true,
seriesDefaults : {
renderer : $.jqplot.BarRenderer,
rendererOptions : {
barMargin : 30,
varyBarColor : true,
highlightMouseDown : true,
barWidth: 60
},
pointLabels : {
show : true
}
},
axes : {
xaxis : {
renderer : $.jqplot.CategoryAxisRenderer,
ticks : months,
tickOptions : {
mark : 'outside'
}
},
yaxis : {
tickOptions : {
show : false
},
padMin : 0
}
},
series : [ {
label : 'bla1'
}, {
label : 'bla2'
}, {
label : 'bla3'
} ],
legend : {
show : true,
location : 'ne',
placement : 'inside'
}
});
});
Thanks!
OK, the solution was a hack which I will show and describe here:
You need to overwrite the function called $.jqplot.BarRenderer.prototype.draw and change some of the lines
You need to overwrite the function called getStart(sidx, didx, comp, plot, axis)
You need to overwrite the function called $.jqplot.ShapeRenderer.prototype.draw and change some of the lines
1.:
$.jqplot.BarRenderer.prototype.draw = function(ctx, gridData, options, plot) {
var i;
// Ughhh, have to make a copy of options b/c it may be
// modified later.
var opts = $.extend({}, options);
.................................
<other code>
.................................
var clr = opts.fillStyle || this.color;
this._dataColors.push(clr);
this.renderer.shapeRenderer.draw(ctx, points, opts, i, pos); // changed line
I changed the line in that way that I added i and pos parameters into the function. The reason was to indicate the current bar and position in the bar.
2.:
function getStart(sidx, didx, comp, plot, axis) {
// check if sign change
var seriesIndex = sidx, prevSeriesIndex = sidx - 1, start, prevVal, aidx = (axis === 'x') ? 0 : 1;
// is this not the first series?
if (seriesIndex > 0) {
prevVal = plot.series[prevSeriesIndex]._plotData[didx][aidx];
// is there a sign change
if ((comp * prevVal) < 0) {
start = getStart(prevSeriesIndex, didx, comp, plot, axis);
}
// no sign change.
else {
start = plot.series[prevSeriesIndex].gridData[didx][aidx];
}
}
// if first series, return value at 0
else {
start = (aidx === 0) ? plot.series[seriesIndex]._xaxis.series_u2p(0) : plot.series[seriesIndex]._yaxis.series_u2p(0);
}
return start;
}
Nothing is changed here. You just need to copy the function because your new overwritten function cannot use it from jQPlot library.
3.:
$.jqplot.ShapeRenderer.prototype.draw = function(ctx, points, options, currentBar, position) {
ctx.save();
var opts = (options != null) ? options : {};
var fill = (opts.fill != null) ? opts.fill : this.fill;
var closePath = (opts.closePath != null) ? opts.closePath : this.closePath;
var fillRect = (opts.fillRect != null) ? opts.fillRect : this.fillRect;
var strokeRect = (opts.strokeRect != null) ? opts.strokeRect
: this.strokeRect;
var clearRect = (opts.clearRect != null) ? opts.clearRect : this.clearRect;
var isarc = (opts.isarc != null) ? opts.isarc : this.isarc;
var linePattern = (opts.linePattern != null) ? opts.linePattern
: this.linePattern;
var ctxPattern = $.jqplot.LinePattern(ctx, linePattern);
ctx.lineWidth = opts.lineWidth || this.lineWidth;
ctx.lineJoin = opts.lineJoin || this.lineJoin;
ctx.lineCap = opts.lineCap || this.lineCap;
ctx.strokeStyle = (opts.strokeStyle || opts.color) || this.strokeStyle;
ctx.fillStyle = opts.fillStyle || this.fillStyle;
if (currentBar == activeColumn && position == 0) { // adding different color for the specific bar
ctx.fillStyle = defaultColors[0];
} else if (currentBar == activeColumn && position == 1) {
ctx.fillStyle = defaultColors[1];
} else if (currentBar == activeColumn && position == 2) {
ctx.fillStyle = defaultColors[2];
}
ctx.beginPath();
if (isarc) {
ctx.arc(points[0], points[1], points[2], points[3], points[4], true);
if (closePath) {
ctx.closePath();
}
if (fill) {
ctx.fill();
} else {
ctx.stroke();
}
ctx.restore();
return;
} else if (clearRect) {
ctx.clearRect(points[0], points[1], points[2], points[3]);
ctx.restore();
return;
} else if (fillRect || strokeRect) {
if (fillRect) {
ctx.fillRect(points[0], points[1], points[2], points[3]);
}
if (strokeRect) {
ctx.strokeRect(points[0], points[1], points[2], points[3]);
ctx.restore();
return;
}
} else if (points && points.length) {
var move = true;
for ( var i = 0; i < points.length; i++) {
// skip to the first non-null point and move to it.
if (points[i][0] != null && points[i][1] != null) {
if (move) {
ctxPattern.moveTo(points[i][0], points[i][1]);
move = false;
} else {
ctxPattern.lineTo(points[i][0], points[i][1]);
}
} else {
move = true;
}
}
if (closePath) {
ctxPattern.closePath();
}
if (fill) {
ctx.fill();
} else {
ctx.stroke();
}
}
ctx.restore();
};
Here you need to check whether the bar your currently at, is the default one. The important part of the code is:
if (currentBar == activeColumn && position == 0) { // adding different color for the specific bar
ctx.fillStyle = defaultColors[0];
} else if (currentBar == activeColumn && position == 1) {
ctx.fillStyle = defaultColors[1];
} else if (currentBar == activeColumn && position == 2) {
ctx.fillStyle = defaultColors[2];
}
I added 3 different colors for that bar just to have "more fancy" diagram :)

Opencart get current layout_id

I have created a custom layout and i planned to hide products only for those custom layout assigned pages.
Is there any way to get current layout id ?
For example, Let's say my custom layout_id is 10, I planned to use some looping like below to hide/show products
if (current_layout_id != 10) {
// Display products
}else {
// Hide Products
}
find layout id of current displayed module page
if (isset($this->request->get['route'])) {
$route = $this->request->get['route'];
} else {
$route = 'common/home';
}
$layout_id = 0;
if (substr($route, 0, 16) == 'product/category' && isset($this->request->get['path'])) {
$path = explode('_', (string)$this->request->get['path']);
$layout_id = $this->model_catalog_category->getCategoryLayoutId(end($path));
}
if (substr($route, 0, 16) == 'product/product' && isset($this->request->get['product_id'])) {
$layout_id = $this->model_catalog_product->getProductLayoutId($this->request->get['product_id']);
}
if (substr($route, 0, 16) == 'product/information' && isset($this->request->get['information_id'])) {
$layout_id = $this->model_catalog_information->getInformationLayoutId($this->request->get['information_id']);
}
if (!$layout_id) { $layout_id = $this->model_design_layout->getLayout($route); }
if (!$layout_id) { $layout_id = $this->config->get('config_layout_id'); }
end of layout id finding

Resources