i just trying to do create image from text input value which i want to transparent background, but somehow somewhere there is a mistake which i couldn't find. http://jsfiddle.net/e4f3Lc6n/
When i change the var backgroundColor = "transparent"; to any color it works like a charm. but you can see in jsfiddle link it is writing over the previous text when it is transparent. For my project there should be no color background. Where am i making a mistake?
Thanks for any help...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Text Arranger</title>
<link rel="stylesheet" href="../poetry/poetry_stylesheet.css" type="text/css"/>
<link rel="stylesheet" href="../index_stylesheet.css" type="text/css"/>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-46245008-1', 'peteymac.com');
ga('send', 'pageview');
</script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);
var Debugger = function() {};
Debugger.log = function(message) {
try {
console.log(message);
} catch (exception) {
return;
}
}
function eventWindowLoaded () {
canvasApp();
}
function canvasSupport () {
return !!document.createElement("canvas").getContext;
}
function canvasApp () {
Debugger.log("Drawing Canvas");
if(!canvasSupport()) {
return;
}
var theCanvas = document.getElementById('canvasOne');
var context = theCanvas.getContext('2d');
WIDTH = theCanvas.width;
HEIGHT = theCanvas.height;
var message = "canberk";
var fontSize = "50";
var fontFace = "serif";
var fontWeight = "normal"
var fontStyle = "normal";
var textFillColor = "#ff0000";
var backgroundColor = "transparent";
var textStrokeColor = "#000000";
var fillOrStroke = "fill";
var textBaseline = "middle";
var textAlign = "center";
var fillType = "colorFill";
// This is the event handler for listening for a key up event in the text box form
// It will call the textBoxChanged function to update the text in the canvas
var formElement = document.getElementById("textBox");
formElement.addEventListener("keyup", textBoxChanged, false);
formElement = document.getElementById("textSize");
formElement.addEventListener("change", textSizeChanged, false);
formElement = document.getElementById("textFont");
formElement.addEventListener("change", textFontChanged, false);
formElement = document.getElementById("fontWeight");
formElement.addEventListener("change", fontWeightChanged, false);
formElement = document.getElementById("fontStyle");
formElement.addEventListener("change", fontStyleChanged, false);
formElement = document.getElementById("fillType");
formElement.addEventListener("change", fillTypeChanged, false);
formElement = document.getElementById("textFillColor");
formElement.addEventListener("change", textFillColorChanged, false);
formElement = document.getElementById("createImageData");
formElement.addEventListener("click", createImageDataPressed, false);
drawScreen();
function drawScreen() {
var metrics = context.measureText(message);
var textWidth = metrics.width;
var xPosition = WIDTH / 2
var yPosition = HEIGHT / 2;
// Draws the Text Box
context.globalAlpha = 1.0;
context.fillStyle = backgroundColor;
context.fillRect(0,0,WIDTH,HEIGHT);
// Draws the actual text
context.font = fontWeight + " " + fontStyle + " " + fontSize + "px " + fontFace;
context.textBaseline = textBaseline;
context.textAlign = textAlign;
var tempColor;
switch(fillType) {
case "colorFill":
Debugger.log("Color Fill");
tempColor = textFillColor;
break;
case "linearGradient":
Debugger.log("Linear Gradient");
var linGradient = context.createLinearGradient(xPosition-textWidth/2, yPosition, xPosition+textWidth/2, yPosition);
linGradient.addColorStop(0, textFillColor);
tempColor = linGradient;
break;
case "radialGradient":
Debugger.log("Radial Gradient");
var radGradient = context.createRadialGradient(xPosition, yPosition, 1, xPosition, yPosition, textWidth/2);
radGradient.addColorStop(0, textFillColor);
tempColor = radGradient;
break;
}
switch(fillOrStroke) {
case "fill":
context.fillStyle = tempColor;
context.fillText(message, xPosition, yPosition);
break;
case "stroke":
context.strokeStyle = textStrokeColor;
context.strokeText(message, xPosition, yPosition);
break;
case "both":
context.fillStyle = tempColor;
context.fillText(message, xPosition, yPosition);
context.strokeStyle = textStrokeColor;
context.strokeText(message, xPosition, yPosition);
break;
}
}
function textBoxChanged(e) {
var target = e.target;
message = target.value;
drawScreen();
}
function textSizeChanged(e) {
var target = e.target;
fontSize = target.value;
drawScreen();
}
function textFontChanged(e) {
var target = e.target;
fontFace = target.value;
drawScreen();
}
function fontWeightChanged(e) {
var target = e.target;
fontWeight = target.value;
drawScreen();
}
function fontStyleChanged(e) {
var target = e.target;
fontStyle = target.value;
drawScreen();
}
function fillTypeChanged(e) {
var target = e.target;
fillType = target.value;
drawScreen();
}
function textFillColorChanged(e) {
var target = e.target;
textFillColor = "#" + target.value;
drawScreen();
}
function createImageDataPressed(e) {
var imageDataDisplay = document.getElementById("imageDataDisplay");
imageDataDisplay.value = theCanvas.toDataURL();
}
}
</script>
<style>
#canvasOne {
box-shadow: -4px -4px 5px #aaaaaa;
display: block;
margin-left: -60px;
}
form {
margin-top: 40px;
}
</style>
</head>
<body>
<canvas id="canvasOne" width="1000" height="250">
Your browser does not support Canvas.
</canvas>
<form>
Text: <input id="textBox" value="canberk"/>
<br/>
Text Font: <select id="textFont">
<option value = "serif">Serif</option>
<option value = "sans-serif">Sans-Serif</option>
<option value = "cursive">Cursive</option>
<option value = "fantasy">Fanatasy</option>
<option value = "monospace">Monospace</option>
</select>
Font Weight: <select id="fontWeight">
<option value="normal">Normal</option>
<option value="bold">Bold</option>
<option value="bolder">Bolder</option>
<option value="lighter">Lighter</option>
</select>
Font Style: <select id="fontStyle">
<option value="normal">Normal</option>
<option value="italic">Italic</option>
<option value="oblique">Oblique</option>
</select>
<br/>
Text Size: <input type="range" id="textSize"
min="0"
max="200"
step="1"
value="50"/>
<br/>
Fill Type: <select id="fillType">
<option value="colorFill">Color Fill</option>
<option value="linearGradient">Linear Gradient</option>
<option value="radialGradient">Radial Gradient</option>
</select>
<br/>
Text Fill Color: <input id="textFillColor" value="ff0000"/>
<input type="button" id="createImageData" value="Create Data Image">
<br/>
<textarea id="imageDataDisplay" rows=5 cols=100></textarea>
</form>
</div>
</body>
</html>
I think the solution you need is:
function drawScreen() {
context.clearRect(0, 0, WIDTH, HEIGHT);
...
...
}
Related
I'm using this code to show images.
The problem is that it is showing popup only for the first image and not the rest.
Images are loaded from database so they all have the same id.
Is that the problem or something else?
Code :
if (ViewBag.ReceptiSearchAll != null)
{
<div class="col-6 col-lg">
#foreach (var images in ViewBag.ReceptiSearchImages)
{
if (images.Image != null)
{
imagePath = images.Image;
}
else
{
imagePath = images.ImageDefault;
}
<div class="card mb-3" style="max-width: 400px;border:none">
<div class="row no-gutters">
<div class="col-md-12">
<img id="imgrec" class="card-img-top" src="data:image;base64,#System.Convert.ToBase64String(imagePath)" alt="Slika recepta" width="250" height="200">
</div>
</div>
</div>
}
</div>
}
<script>
// Get the modal
var modal = document.getElementById("myModal");
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("imgrec");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
}
</script>
All your images have the same id.
<img id="imgrec" ...
id is meant to be a unique identifier.
var img = document.getElementById("imgrec");
For that reason, only your first image gets this.
img.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
I'm having trouble making my chart responsive, I'm trying to apply the same example with DC.js and Crossfilter that is at this link: resizing-series.
The chart is responsive, however, there are some bugs when interacting with the tables I have. For example, when I click on either the graph or any of the tables, the graph becomes very large, occupying the entire screen. As shown in the image below:
When I leave the screen split with Console, the graph is rendered responsively, as I change the screen size the size of the graph is also changed, however, if I leaveConsole the graph remains occupying the entire the screen and does not return to the default initial size shown in the first image.
Does anyone know how to tell me how to fix these bugs? I couldn't understand why this is happening.
Thnaks in advance.
var composite = dc.compositeChart('#composite');
var vendedorTable = dc.dataTable("#vendedores");
var citiesTable = dc.dataTable("#cities");
function remove_empty_bins(source_group) {
return {
top: function(N) {
return source_group.all().filter(function(d) {
return d.value.totalAno > 1e-3 ||
d.value.totalHomologo > 1e-3;
}).slice(0, N);
}
};
}
var url = 'https://gist.githubusercontent.com/bernalvinicius/3cece295bc37de1697e7f83418e7fcc9/raw/a5820379ec6eae76ee792495cc5dd1685c977a73/vendedores.json';
d3.json(url).then(function(data) {
data.forEach(d =>
Object.assign(d, {
mes: d.Month,
atual: d.Vendas_Ano,
passado: d.Vendas_Ant
})
);
var cf = crossfilter(data);
vendedorDim = cf.dimension(function(d) {
return d.vendnm;
});
var vendedorGroup = vendedorDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);
citiesDim = cf.dimension(function(d) {
return d.zona;
});
var citiesGroup = citiesDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);
var dim = cf.dimension(dc.pluck('mes')),
grp1 = dim.group().reduceSum(dc.pluck('atual')),
grp2 = dim.group().reduceSum(dc.pluck('passado'));
var minMonth = dim.bottom(1)[0].mes;
var maxMonth = dim.top(1)[0].mes;
var all = cf.groupAll();
dc.dataCount(".dc-data-count")
.dimension(cf)
.group(all);
function reduceAdd(p, v) {
p.totalAno += +v.Vendas_Ano;
p.totalHomologo += +v.Vendas_Ant;
return p;
}
function reduceRemove(p, v) {
p.totalAno -= v.Vendas_Ano;
p.totalHomologo -= v.Vendas_Ant;
return p;
}
function reduceInitial() {
return {
totalAno: 0,
totalHomologo: 0,
};
}
// Fake Dimension
rank = function(p) {
return ""
};
// Chart by months
composite
.width(600)
.height(300)
.x(d3.scaleLinear().domain([1, 12]))
.yAxisLabel("")
.xAxisLabel("Month")
.legend(dc.legend().x(500).y(0).itemHeight(13).gap(5))
.renderHorizontalGridLines(true)
.compose([
dc.lineChart(composite)
.dimension(dim)
.colors('steelblue')
.group(grp1, "Currently Year"),
dc.lineChart(composite)
.dimension(dim)
.colors('darkorange')
.group(grp2, "Last Year")
])
.brushOn(true);
composite.brush().extent([-0.5, data.length + 1.5])
composite.extendBrush = function(brushSelection) {
if (brushSelection) {
vendedorTable.filter(null);
vendedorDim.filter(null);
citiesTable.filter(null);
citiesDim.filter(null);
const point = Math.round((brushSelection[0] + brushSelection[1]) / 2);
return [
point - 0.5,
point + 0.5
];
}
};
// Sales Table
vendedorTable.width(500)
.height(480)
.dimension(remove_empty_bins(vendedorGroup))
.group(rank)
.columns([function(d) {
return d.key;
},
function(d) {
return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
minimumFractionDigits: 2
}) + '€';
},
function(d) {
return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
minimumFractionDigits: 2
}) + '€';
}
])
.sortBy(function(d) {
return d.value.totalAno
})
.order(d3.descending)
// Cities Table
citiesTable.width(500)
.height(480)
.dimension(remove_empty_bins(citiesGroup))
.group(rank)
.columns([function(d) {
return d.key;
},
function(d) {
return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
minimumFractionDigits: 2
}) + '€';
},
function(d) {
return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
minimumFractionDigits: 2
}) + '€';
}
])
.sortBy(function(d) {
return d.value.totalAno
})
.order(d3.descending)
// Sales click events
vendedorTable.on('pretransition', function(table) {
table.selectAll('td.dc-table-column')
.on('click', function(d) {
let filters = table.filters().slice();
if (filters.indexOf(d.key) === -1)
filters.push(d.key);
else
filters = filters.filter(k => k != d.key);
if (filters.length === 0)
vendedorDim.filter(null);
else
vendedorDim.filterFunction(function(d) {
return filters.indexOf(d) !== -1;
})
table.replaceFilter([filters]);
citiesTable.filter(null);
citiesDim.filter(null);
composite.filter(null);
dc.redrawAll();
});
let filters = table.filters();
table.selectAll('tr.dc-table-row')
.classed('sel-rows', d => filters.indexOf(d.key) !== -1);
});
// Cities click events
citiesTable.on('pretransition', function(table) {
table.selectAll('td.dc-table-column')
.on('click', function(d) {
let filters = table.filters().slice();
if (filters.indexOf(d.key) === -1)
filters.push(d.key);
else
filters = filters.filter(k => k != d.key);
if (filters.length === 0)
citiesDim.filter(null);
else
citiesDim.filterFunction(function(d) {
return filters.indexOf(d) !== -1;
})
table.replaceFilter([filters]);
vendedorTable.filter(null);
vendedorDim.filter(null);
composite.filter(null);
dc.redrawAll();
});
let filters = table.filters();
table.selectAll('tr.dc-table-row')
.classed('sel-rows', d => filters.indexOf(d.key) !== -1);
});
dc.renderAll();
// reset functions
$('#reset').on('click', function() {
vendedorTable.filter(null);
vendedorDim.filter(null);
citiesTable.filter(null);
citiesDim.filter(null);
composite.filter(null);
dc.redrawAll();
});
$('#resetTable').on('click', function() {
vendedorTable.filter(null);
vendedorDim.filter(null);
citiesTable.filter(null);
citiesDim.filter(null);
composite.filter(null);
dc.redrawAll();
});
$('#resetTable2').on('click', function() {
vendedorTable.filter(null);
vendedorDim.filter(null);
citiesTable.filter(null);
citiesDim.filter(null);
composite.filter(null);
dc.redrawAll();
});
/****************************************************************************/
// Functions to handle responsive
var adjustX = 10,
adjustY = 40;
apply_resizing(composite, adjustX, adjustY, function(composite) {
composite.legend().x(window.innerWidth - 200);
});
var find_query = function() {
var _map = window.location.search.substr(1).split('&').map(function(a) {
return a.split('=');
}).reduce(function(p, v) {
if (v.length > 1)
p[v[0]] = decodeURIComponent(v[1].replace(/\+/g, " "));
else
p[v[0]] = true;
return p;
}, {});
return function(field) {
return _map[field] || null;
};
}();
var resizeMode = find_query('resize') || 'widhei';
function apply_resizing(composite, adjustX, adjustY, onresize) {
if (resizeMode === 'viewbox') {
composite
.width(300)
.height(200)
.useViewBoxResizing(true);
d3.select(composite.anchor()).classed('fullsize', false);
} else {
adjustX = adjustX || 0;
adjustY = adjustY || adjustX || 0;
composite
.width(window.innerWidth - adjustX)
.height(window.innerHeight - adjustY);
window.onresize = function() {
if (onresize) {
onresize(composite);
}
composite
.width(window.innerWidth - adjustX)
.height(window.innerHeight - adjustY);
if (composite.rescale) {
composite.rescale();
}
composite.redraw();
};
}
}
});
#composite {
padding: 10px;
}
.dc-table-group {
visibility: collapse;
}
tr.dc-table-row.sel-rows {
background-color: lightblue;
}
.brush .custom-brush-handle {
display: none;
}
<!-- favicon -->
<link rel="shortcut icon" href="https://img.icons8.com/nolan/64/puzzle.png">
<!-- bootstrap.css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- bootstrap-theme.css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- dc.css -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.8/dc.css">
<!-- jquery.js -->
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<!-- bootstrap.js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- d3.v5.js -->
<script src="https://d3js.org/d3.v5.js"></script>
<!-- crossfilter.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.js"></script>
<!-- dc.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/dc/3.1.8/dc.js"></script>
<title>12</title>
</head>
<body>
<div class="container-fluid">
<div class="row content">
<div class="col-md-10">
<div class="col-md-4">
<div id="composite"></div>
</div>
</div>
</div>
<div class="row content">
<div class="col-md-10">
<div style="padding: 20px;;" class="row marginClass">
<h4 class="pull-left" id="Introduction">
<small>Fictitious company data | Drilldown Example |</small>
</h4>
<h6 class="dc-data-count" style="float: left;margin-left:5px;">
<span>
<span class="filter-count"></span> selected from
<span class="total-count"></span> records |
<a id="reset"> Reset </a>
</span>
</h6>
</div>
<div class="col-md-4">
<table class="table" id="vendedores">
<thead>
<tr>
<th>Sales</th>
<th>Current Year</th>
<th>Last Year</th>
</tr>
</thead>
</table>
</div>
<div class="col-md-4">
<table class="table" id="cities">
<thead>
<tr>
<th>City</th>
<th>Current Year</th>
<th>Last Year</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</body>
Thanks for posting an example! The bug doesn't show up in the SO code snippet feature unless you go to full page mode. I found your fiddle easier to work with.
Note: this is a complete rewrite of my previous answer, which was not clear.
1. Using ResizeObserver
updated 4/28/20
As of Safari 13.1 (released March 24 2020) all modern browsers support ResizeObserver. This is the cleanest way to detect chart resizing.
I recommend
Use a top-down layout such as flexbox or grid to position the divs for your charts
Use ResizeObserver to determine when the div has changed size
Tell the charts to detect the chart div size using .width(null).height(null)
There is currently one resizing example that does this.
The special value null tells the chart to make the SVG node the same size as its parent div:
chart1.width(null)
.height(null)
The callback uses a helper function to disable transitions, because transitions just slow resizing down and make it look clunky:
const callback = chart => entries => {
redraw_chart_no_transitions(
chart
.width(null)
.height(null)
.rescale());
};
Setting up the observer looks like
new ResizeObserver(callback(chart1)).observe(d3.select('#test1').node());
Please see the example for more details.
2. Using window.onresize
The other resizing examples watch for window.onresize because until recently that was the only efficient, reliable cross-browser way to detect changes.
They calculate chart sizes based on the window size, which works well if your layout is bottom-up, e.g. using the default float: left layout.
Here is the function which sets this up:
function apply_resizing(chart, adjustX, adjustY, onresize) {
if(!Array.isArray(chart))
chart = [chart];
if(!isNaN(adjustX))
adjustX = (dx => x => x-dx)(adjustX);
adjustX = adjustX || (x => x);
if(!isNaN(adjustY))
adjustY = (dy => y => y-dy)(adjustY);
adjustY = adjustY || adjustX || (y => y);
chart.forEach(c => c.width(adjustX(window.innerWidth))
.height(adjustY(window.innerHeight)));
window.onresize = function () {
if (onresize) {
chart.forEach(onresize);
}
chart.forEach(c => {
c.width(adjustX(window.innerWidth))
.height(adjustY(window.innerHeight));
if (c.rescale) {
c.rescale();
}
});
redraw_chart_no_transitions(chart);
};
}
A single chart can be initialized like so:
apply_resizing(chart, 20);
This fills the window but makes the chart 20 pixels less wide.
The function can also take multiple charts in an array, and adjustment functions to support complicated layouts, like one where two charts should split the window vertically:
apply_resizing([heatmapChart, barChart], 20, y => y/2-fudge);
I try to automate the CMS using robot framework, I got the XPath using firepath, I'm able to locate the element in Firefox, if I refresh the page, I couldn't locate the same XPath,I thought XPath got changed, but I got the same XPath when I try to get after page refresh,
IN SHORT again:
1) Got the Xpath, say "A"
2) Refresh the page
3) try to locate the element using "A".but it shows no element found
4) Get the new XPath, say "B"
5) Both A and B are same if I try now with A it works,
I need to automate this scenario, Thanks for your time.
I tried Frame too.
Note:
Every time after refresh element gets hidden until the click operation takes place.
<document>
<html style="height: 100%; overflow: hidden;">
<head>
**xpath**<body id="m_bodyElem" class="Gecko Gecko54 ENUS cms-bootstrap ui-layout-container" style="position: relative; height: 100%; overflow: hidden; margin: 0px; padding: 0px; border: medium none;">
<form id="aspnetForm" method="post" action="./CMSAdministration.aspx">
<div class="aspNetHidden">**xpath**
***
</document>
AFTER DOM ACTIVATION
<document>
<html>
<head>
<body id="m_bodyElem" class="Gecko Gecko54 ENUS cms-bootstrap">
<form id="aspnetForm" method="post" action="./UIPage.aspx?elementguid=a5568855-b030-47ff-801a-d524618a2ca7&displaytitle=false" onsubmit="if (window.Loader) { window.Loader.submitForm(1000, false); }; return true;">
<div class="aspNetHidden">
<script type="text/javascript"> //<![CDATA[ var theForm = document.forms['aspnetForm']; if (!theForm) { theForm = document.aspnetForm; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]> </script>
<script src="/WebResource.axd?d=pynGkmcFUV13He1Qd6_TZBvGXq_vBGigUCFpfznup-OhZmSOTsQXuUy4Gn5GLidTPeGZMHkjMcSO21b0MZpf4w2&t=636160552680000000" type="text/javascript"/>
<script type="text/javascript"> //<![CDATA[ function CloseDialog(refreshPage) { // Check that the document content has not been changed without saving. Stop closing the dialog when user decides to save the content. if (window.CheckChanges && !CheckChanges()) { return false; } if (typeof(refreshPage) === "undefined") { refreshPage = true; } try { // IE9 fix - wopener doesn't have to be available if(refreshPage && window.wopener && window.wopener.RefreshWOpener) { wopener.RefreshWOpener(window); } } catch(err) {} var canClose = true; if (window.onCloseDialog) { canClose = window.onCloseDialog(); } if (canClose) { if(top.closeDialog && (top != window)) { setTimeout(function(){ if(top && top.closeDialog && (top != window)){ top.closeDialog(window) } }, 1); } else { top.close(); } } return false; } //]]> </script>
<script type="text/javascript"> //<![CDATA[ function GetTop(){ if(top.getTop) { return top.getTop(window); } else { return top; } } //]]> </script>
<script src="/CMSPages/GetResource.ashx?scriptfile=%2fCMSScripts%2fUI%2fUIPage.js" type="text/javascript"/>
<script type="text/javascript"> //<![CDATA[ function ToggleDiv(label){ var div = $cmsj(label).parent(); var image = div.find('.ToggleImage'); var hiddenField = image.next(); var affectedElements = div.find('.editing-form-category-caption').next(); if(hiddenField.val() == 'True') { div.removeClass('Collapsed'); hiddenField.val('False') image.attr('src', '/CMSPages/GetResource.ashx?image=%5bImages.zip%5d%2fCMSModules%2fCMS_PortalEngine%2fWebpartProperties%2fminus.png'); affectedElements.show(); } else { div.addClass('Collapsed'); hiddenField.val('True'); image.attr('src', '/CMSPages/GetResource.ashx?image=%5bImages.zip%5d%2fCMSModules%2fCMS_PortalEngine%2fWebpartProperties%2fplus.png'); affectedElements.hide(); } } //]]> </script>
<script type="text/javascript"> //<![CDATA[ function modalDialog(url, name, width, height, otherParams, noWopener, forceModal, forceNewWindow, setTitle) { // Header and footer is greater than before, increase window size accordingly if (typeof(height) === "number") { height += 66; } // Set default parameter values if (setTitle == undefined) { setTitle = true; } if (forceModal == undefined) { forceModal = true; } if (otherParams == undefined) { otherParams = 'toolbar=no,directories=no,menubar=no,modal=yes,dependent=yes,resizable=yes'; } var advanced = false; try { advanced = window.top.AdvancedModalDialogs; } catch (err) { } if (advanced && !forceNewWindow) { window.top.advancedModal(url, name, width, height, otherParams, noWopener, forceModal, setTitle, this); } else { var dHeight = height; var dWidth = width; if (width.toString().indexOf('%') != -1) { dWidth = Math.round(screen.width * parseInt(width, 10) / 100); } if (height.toString().indexOf('%') != -1) { dHeight = Math.round(screen.height * parseInt(height, 10) / 100); } var oWindow = window.open(url, name, 'width=' + dWidth + ',height=' + dHeight + ',' + otherParams); if (oWindow) { oWindow.opener = this; oWindow.focus(); } } } //]]> </script>
<script type="text/javascript"> //<![CDATA[ var applicationUrl = '/'; var imagesUrl = '/CMSPages/GetResource.ashx?image=%5bImages.zip%5d%2f'; var isRTL = false; //]]> </script>
<script src="/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fBootstrap%2fbootstrap.min.js" type="text/javascript"/>
<script src="/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fBootstrap%2fbootstrap.custom.js" type="text/javascript"/>
<script src="/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fControls%2fcontextmenu.js" type="text/javascript"/>
<script type="text/javascript"> //<![CDATA[ menuSettings['cg0_motheractions'] = { activecss : 'unigrid-action-menuactive', inactivecss : '', activecssoffset : 0, button : 'Both', vertical : 'Bottom', offsetx : 0, offsety : 0, horizontal : 'Left', dynamic : false, mouseover : false, level : 0, rtl : false, up : false }; CM_Init('cg0_motheractions'); function ContextMenuAsyncCloser_cg0_motheractions(sender, args) { HideContextMenu('cg0_motheractions',true); } RegisterAsyncCloser(ContextMenuAsyncCloser_cg0_motheractions); //]]> </script>
<script type="text/javascript"> //<![CDATA[ function ContextExportObject(definition, backup) { var query = ''; if (backup) { query += '&backup=true'; } modalDialog(applicationUrl + 'CMSModules/ImportExport/Pages/ExportObject.aspx?objectType=' + escape(definition[0]) + '&objectId=' + definition[1] + query, 'ExportObject', 750, 230); } function ContextRestoreObject(definition, backup) { var query = '&ug=UG_m_c_plc_lt_ctl01_ST_UI_Listing_gridElem'; if (backup) { query += '&backup=true'; } modalDialog(applicationUrl + 'CMSModules/ImportExport/Pages/RestoreObject.aspx?objectType=' + escape(definition[0]) + '&objectId=' + definition[1] + query, 'RestoreObject', 750, 400); } function ContextCloneObject(definition) { modalDialog(applicationUrl + 'CMSModules/Objects/Dialogs/CloneObjectDialog.aspx?objectType=' + escape(definition[0]) + '&objectId=' + definition[1], 'CloneObject', 750, 470); } //]]> </script>
<script type="text/javascript"> //<![CDATA[ menuSettings['cg0_mActions'] = { activecss : 'unigrid-menu-panel', inactivecss : 'unigrid-menu-panel', activecssoffset : 0, button : 'Both', vertical : 'Bottom', offsetx : 0, offsety : 0, horizontal : 'Left', dynamic : false, mouseover : false, level : 0, rtl : false, up : false }; CM_Init('cg0_mActions'); function ContextMenuAsyncCloser_cg0_mActions(sender, args) { HideContextMenu('cg0_mActions',true); } RegisterAsyncCloser(ContextMenuAsyncCloser_cg0_mActions); //]]> </script>
<script src="/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fjquery%2fjquery-dialog.js" type="text/javascript"/>
<script src="/ScriptResource.axd?d=x6wALODbMJK5e0eRC_p1LReXSSMeIyuHkoW0S0JbeJThyUVM1Ht4tiF1s3IQMCFhPQK_xpltR2WGldkDgz-jn22orun3s0371LlvE1PAZKjo6kObtvOl-fuKz6i7Aya00&t=7c776dc1" type="text/javascript"/>
<script src="/ScriptResource.axd?d=P5lTttoqSeZXoYRLQMIScL2FKbXixpOQbTl1EIUzR5PmuwyrWWddMW5IgYL1QiI9_cn_1H5B6OyKNQvmWuhRMgoFqxMQlu84DtMU2tQiSt_N7pheWxn0ZjjBaQY6SWz90&t=7c776dc1" type="text/javascript"/>
<script type="text/javascript"> //<![CDATA[ var CMS = CMS || {}; CMS.Application = { "applicationName": "PIM", "imagesUrl": "/CMSPages/GetResource.ashx?image=%5bImages.zip%5d%2f", "isDebuggingEnabled": false, "contexthelp": { "contextHelp": { "application": { "description": null, "helpTopics": [] }, "helpTopics": [] }, "suppressContextHelp": false }, "applicationUrl": "/", "isDialog": false, "isRTL": "false" }; //]]> </script>
<div class="aspNetHidden">
<script type="text/javascript"> //<![CDATA[ Sys.WebForms.PageRequestManager._initialize('m$manScript', 'aspnetForm', ['tm$c$plc$lt$ctl00$HeaderActions$headerElem$pnlUp','','tm$c$plc$lt$ctl01$ST_UI_Listing$gridElem$a$pnlUpdate','','tm$c$ctxM','','tm$pM$pMP','','tm$c$plc$lt$ctl01$MessagesPlaceholder$plcMess$pMP','','tm$c$plc$lt$ctl01$ST_UI_Listing$gridElem$plcMess$pMP',''], [], [], 90, 'm'); //]]> </script>
<div id="m_pnlBody" class="PageBody">
<div id="m_pM_pMP"/>
<div id="m_c_m"/>
<div id="m_c_ctxM">
<div id="UIHeader" class="UIHeader">
<div id="m_c_plc_lt_ctl00_HeaderActions_headerElem_pnlUp">
<div id="m_c_plc_lt_ctl00_HeaderActions_headerElem_pnlActions" class="header-actions-container">
<button id="m_c_plc_lt_ctl00_HeaderActions_headerElem_headerElem_HA_0" class="btn btn-primary" type="button" name="m$c$plc$lt$ctl00$HeaderActions$headerElem$headerElem_HA_0" value="New Product Type" onclick="window.open('/CMSModules/AdminControls/Pages/UIPage.aspx?elementguid=6e43429b-1086-4669-8130-9ee24ebb1d21&displaytitle=false','_self'); return false;__doPostBack('m$c$plc$lt$ctl00$HeaderActions$headerElem$headerElem_HA_0','')">New Product Type</button>
</div>
<div id="m_c_plc_lt_ctl00_HeaderActions_headerElem_pnlAdditionalControls" class="dont-check-changes "/>
</div>
<div id="m_c_plc_lt_ctl00_HeaderActions_HeaderActions_zone_PageTitle_pnlHeader" class="PageHeader SimpleHeader">
<div id="CMSHeaderDiv" class="CMSHeaderDiv"/>
<div id="CKToolbar" class="CKToolbar"/>
</div>
<div id="UIContent" class="UIContent scroll-area" style="height: auto; top: 56px; bottom: 0px;">
</div>
<script type="text/javascript"> //<![CDATA[ (function() {var fn = function() {$get("m_manScript_HiddenField").value = '';Sys.Application.remove_init(fn);};Sys.Application.add_init(fn);})();//]]> </script>
<script type="text/javascript"> //<![CDATA[ document.pageLoaded = true; //]]> </script>
<script type="text/javascript"> //<![CDATA[ cmsrequire(['CMS/UniGrid'], function(module) { new module({ "id": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem", "uniqueId": "m$c$plc$lt$ctl01$ST_UI_Listing$gridElem", "hdnCmdNameId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_hidCmdName", "hdnCmdArgId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_hidCmdArg", "hdnSelHashId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_hidSelectionHash", "hdnSelId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_hidSelection", "gridId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_v", "resetSelection": false, "allowSorting": false }); }); //]]> </script>
<script type="text/javascript"> //<![CDATA[ cmsrequire(['CMS/AdvancedExport'], function(module) { new module({ "id": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a", "uniqueId": "m$c$plc$lt$ctl01$ST_UI_Listing$gridElem$a", "unigridId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem", "hdnParamId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_hdnParameter", "btnFullPostbackUniqueId": "m$c$plc$lt$ctl01$ST_UI_Listing$gridElem$a$btnFullPostback", "chlColumnsId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_chlColumns", "hdnDefaultSelectionId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_hdnDefaultSelection", "revRecordsId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_revRecords", "cvColumnsId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_cvColumns", "mdlAdvancedExportId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_mdlAdvancedExport", "fixHeight": false, "alertMessage": null }); }); //]]> </script>
The button I need to interact is
//button[#id='m_c_plc_lt_ctl00_HeaderActions_headerElem_headerElem_HA_0']
I could add buttons on forms but I wanna know how can I add a button just next the print or create button on a tree view. Is it possible?
in Odoo 10. My code to add a dropdown list:
You can do this: static/xml/my_btn_temp.xml
<?xml version="1.0" encoding="utf-8" ?>
<templates id="template" xml:space="preserve">
<t t-extend="ListView.buttons">
<t t-jquery="button.o_list_button_discard" t-operation="after">
<t t-if="widget.model=='product.template'">
<select class="oe_my_priceliste_button btn btn-sm btn-primary" name="oe_my_priceliste_button" id="oe_my_priceliste_button"
style="margin-left:7%;width:45%;display:inline-block;border: 1px solid #CCCCCC; border-radius: 3px; background: orange;color:white;">
</select>
</t>
</t>
</t>
</templates>
And add this qweb to __manifest__.py:
'data': [....],
'qweb': ['static/xml/my_btn_temp.xml',],
And to add actions to this button, you can do it with JS:
odoo.define('my_module.btn_price_list_tree', function(require) {
"use strict";
var core = require('web.core');
var utils = require('web.utils');
var Model = require('web.Model');
var Widget = require('web.Widget');
var ViewManager = require('web.ViewManager');
var ControlPanel = require('web.ControlPanel');
var ListView = require('web.ListView');
var dataset = require('web.data');
var Dialog = require('web.Dialog');
var list_widget_registry = core.list_widget_registry;
var QWeb = core.qweb;
var _t = core._t;
ListView.include({
load_list: function(data) {
var self = this;
var result = this._super.apply(this, arguments);
var CHOICE = _t("Choose a price list");
var op_tions = "<option value='-1'>"+CHOICE+"</option>";
if (this.$el) {
new Model("product.pricelist").query().all().then(function(ret){
if(ret){
for(var ind=0; ind< ret.length; ind++){
var res = ret[ind];
op_tions += "<option value='"+res.id+"'>"+res.name+"</option>";
}
$('#oe_my_priceliste_button').html(op_tions);
}
});
}
return result;
},
render_buttons: function() {
var self = this;
var add_button = false;
if (!this.$buttons) { // Ensures that this is only done once
add_button = true;
}
this._super.apply(this, arguments); // Sets this.$buttons
if(add_button) {
this.$buttons.on('change', '.oe_my_priceliste_button', this.proxy('do_price_list_dropdown_change'));
}
},
do_price_list_dropdown_change: function(){
var price_list_id = $('#oe_my_priceliste_button').val();
new Model("product.template").call("do_price_list_dropdown_change",[[],price_list_id], {}, {async: true}).done(function(data) {
window.location.reload(true);
});
},
});
});
And you add your js with: /views/assets.js
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data>
<template id="assets_backend" name="project assets" inherit_id="web.assets_backend">
<xpath expr="." position="inside">
<script type="text/javascript" src="/plw_core/static/src/js/add_pricelist_dropdown.js"></script>
</xpath>
</template>
</data>
</odoo>
Thanks.
based of this answer
I have a bootstrap modal that I used that function for that.
Here is the code:
Modal view file:
<div class="modal modal-wide fade" id="mo-selector-dialog" title="<bean:message key="add.ex"/>">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add</h4>
</div>
<div class="modal-body">
<table id="moTable"></table>
<!-- <div id="pager"></div>-->
<div class="modal-footer">
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Modal call in js file:
$('#add-link').click(function(){
$('#mo-selector-dialog').css("display", "block");
$('.mo-backdrop').css("display", "block");
mc$('#mo-selector-dialog').modal({show:true});
$('body').css("overflow-y", "hidden");
});
jqgrid:
$moGrid.bind("jqGridAfterLoadComplete jqGridRemapColumns", function () {
var $this = $(this),
$cells = $this.find(">tbody>tr.jqgrow>td"),
$colHeaders = $($.map(this.grid.headers, function (item) { return item.el; })).find(">div"),
colModel = $this.jqGrid("getGridParam", "colModel"),
cellLayout = $this.jqGrid("getGridParam", "cellLayout"),
iCol,
iRow,
rows,
row,
n = $.isArray(colModel) ? colModel.length : 0,
cm,
colWidth,
idColHeadPrexif = "jqgh_" + this.id + "_";
$cells.wrapInner("<span class='mywrapping'></span>");
$colHeaders.wrapInner("<span class='mywrapping'></span>");
for (iCol = 0; iCol < n; iCol++) {
cm = colModel[iCol];
if (cm.hidden) {
continue;
}
colWidth = $("#" + idColHeadPrexif + $.jgrid.jqID(cm.name) + ">.mywrapping").outerWidth(true) + 25; // 25px for sorting icons
for (iRow = 0, rows = this.rows; iRow < rows.length; iRow++) {
row = rows[iRow];
if ($(row).hasClass("jqgrow")) {
colWidth = Math.max(colWidth, $(row.cells[iCol]).find(".mywrapping").outerWidth(true));
}
}
$this.jqGrid("setColWidth", iCol, colWidth + ($.jgrid.cell_width? cellLayout: 0));
}
});
$moGrid.jqGrid({
height: 400,
url: 'ex/list',
sortname: 'bDt',
colNames: IS.mo.columnDisplayNames,
colModel: IS.mo.colModelDef,
beforeSelectRow: shiftSelect,
gridview: true,
rowattr: function (rd) {
return rowStyle(rd);
},
beforeRequest: IS.filter.applyFilter($moGrid, $('input, select', filterForm), IS.mo.listFilterValues),
onSelectRow: function(id, status) {
$('#messageBox ul').empty();
if (status){
var ids= $moGrid.jqGrid('getGridParam','selarrrow');
for (var i = 0; i < ids.length; i++)
{
var rowId = ids[i];
var rowData = $moGrid.jqGrid ('getRowData', rowId);
global_selectedGroupMRowData.push(rowData);
}
}else{
global_selectedGroupMRowIds.splice($.inArray(id, global_selectedGroupMRowIds), 1);
for(var i=0; i<global_selectedGroupMRowData.length; i++){
if (global_selectedGroupMRowData[i].id==id){
global_selectedGroupMRowData.splice(i, 1);
}
}
//global_selectedGroupMRowData.splice($.inArray($("#moTable").jqGrid('getRowData',id), global_selectedGroupMRowData), 1);
}
},
onSelectAll: function(aRowids, status) {
$('#messageBox ul').empty();
if (status){
for (var i = 0; i < aRowids.length; i++)
if ($.inArray(aRowids[i], global_selectedGroupMRowIds) == -1) {
global_selectedGroupMRowIds.push(aRowids[i]);
global_selectedGroupMRowData.push($("#moTable").jqGrid('getRowData',aRowids[i]));
}
} else {
for (var i = 0; i < aRowids.length; i++) {
global_selectedGroupMRowIds.splice($.inArray(aRowids[i], global_selectedGroupMRowIds), 1);
global_selectedGroupMRowData.splice($.inArray(aRowids[i], global_selectedGroupMRowData), 1);
}
}
},
loadComplete: function() {
var arraysize = global_selectedGroupMRowIds.length;
if (arraysize>0){
for (var i=0; i<arraysize; i++) {
$("#moTable").setSelection(global_selectedGroupMRowIds[i], false);
}
}
getEditPage('#moTable');
$("#moTable").find('#pager_left,#pager_center,#pager_right').hide();
}
});
It works to other pages that aren't modal. Just inside the modal it doesn't work.
Any idea?
I suppose that the problem can be fixed by changing the line
$this.jqGrid("setColWidth", iCol, colWidth + ($.jgrid.cell_width? cellLayout: 0));
so that colWidth will be increased to this.p.cellLayout (cellLayout parameter which equal to 5) if $.jgrid.cell_width is true:
$grid.on("jqGridAfterLoadComplete jqGridRemapColumns", function () {
var $this = $(this),
$cells = $this.find(">tbody>tr.jqgrow>td"),
$colHeaders = $($.map(this.grid.headers, function (item) { return item.el; })).find(">div"),
colModel = $this.jqGrid("getGridParam", "colModel"),
cellLayout = $this.jqGrid("getGridParam", "cellLayout"),
iCol,
iRow,
rows,
row,
n = $.isArray(colModel) ? colModel.length : 0,
cm,
colWidth,
idColHeadPrexif = "jqgh_" + this.id + "_";
$cells.wrapInner("<span class='mywrapping'></span>");
$colHeaders.wrapInner("<span class='mywrapping'></span>");
for (iCol = 0; iCol < n; iCol++) {
cm = colModel[iCol];
if (cm.hidden) {
continue;
}
colWidth = $("#" + idColHeadPrexif + $.jgrid.jqID(cm.name) + ">.mywrapping").outerWidth(true) + 25; // 25px for sorting icons
for (iRow = 0, rows = this.rows; iRow < rows.length; iRow++) {
row = rows[iRow];
if ($(row).hasClass("jqgrow")) {
colWidth = Math.max(colWidth, $(row.cells[iCol]).find(".mywrapping").outerWidth(true));
}
}
$this.jqGrid("setColWidth", iCol, colWidth + ($.jgrid.cell_width? cellLayout: 0));
}
});
The demo uses Bootstrap 3.2 and Font Awesome 4.2. Another demo uses the same code to autowidth of columns and it works too.
UPDATED: See one more demo.