How do I know which element is modifying in contentEditable case? - contenteditable

I have a little problem / question. I work on a little WYSIWYG editor. I use a div with the option contentEditable="true" and I would like to know when there is a click on a button which element in my div is modifying by the user.
For example if there is 3 paragraphs on the the div, and that user modifies the second, I would like to know when he clicks on a button that he is currently to modify the second paragraph to show the text content ! In this example "P2" :
<div contenteditable="true"><p>P1</p><p>P2</p><p>P3</p></div>
Thanks in advance for your help.
Nicolas

You could examine the selection in the mousedown event of the button. The following will work in all major browsers:
function getSelectionBoundaryContainerElement(start) {
var container = null;
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0);
range.collapse(start);
container = range.startContainer;
if (container.nodeType != 1) {
container = container.parentNode;
}
}
} else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
var textRange = document.selection.createRange();
textRange.collapse(start);
container = textRange.parentElement();
}
return container;
}
document.getElementById("yourButtonId").onmousedown = function() {
alert(getSelectionBoundaryContainerElement().innerHTML);
}

Related

Wheelnav.js, not clickable NavItems

I've started using Wheelnav.js. Currently my Wheel is toogled on/off with pressing and releasing X. I also got some hover effects, my Problem is that my NavItems are Clickable.. if i click a item it is "selected" and i cant hover over it anymore.
https://gyazo.com/29f73fd2fb0f8bbf1f634931686c3ec6
In this example i clicked on Item1
You have to set the selected property to false and refresh the wheel.
window.onload = function () {
wheel = new wheelnav("wheelDiv");
wheel.createWheel();
wheel.animateFinishFunction = disableSelected;
};
var disableSelected = function () {
for (var i = 0; i < this.navItemCount; i++) {
if (this.navItems[i].selected) {
this.navItems[i].selected = false;
this.navItems[i].refreshNavItem(true);
}
}
}

Items alignment in the PopupMenuBarItem

I'm absolutely newbie in the Dojo, so my question may be too evident. Sorry.
I've programmatically created the complex menu, including MenuBar, based on the rows, selected from the DB.
All problems were solved besides one: the alignment of the final items and submenu items differ.How it looks like All submenus primarily were rendered in the same line. Only by adding the MenuSeparator I was able to divide them.
I'm lost I've found the example in the Internet, that shows exactly what I need (including the right-hand arrow for submenus) Example . I've used exactly the same algorithm to create menu. But I cannot get the same result.
Please, help.
I've noted that the image is not accessible.
In pure text it looks like:
Final 1
Final 2
Final 3
DropDown 1
DropDown 2
Indent depends on the submenu width.
Think, now I know what happened (don't know though, how to work around it).
The problem is the widget rendering.
The final menu option (leaf) is rendered as table row (tr and td tags).
The PopupMenuItem is rendered as div between rows.
Once more, I have no clue, how to avoid it.
Here is the code. A couple of notes:
1.The rows is the two dimensional array
2.The rows with ParentID=0 are the MenuBarItems
3.pM is the MenuBar widget
createMenu: function (rows, pM) {
var me = this; // for references from the event handlers, where 'this' means event origin (instead of lang.hitch)
// First define the indexes of the DB fields
var xMenu_Id;
var xMenu_Title;
var xParent;
var xURL;
var xUser_Roles;
var i;
for (i = 0; i < rows[0].length; i++) {
switch (rows[0][i]) {
case 'Menu_Id':
xMenu_Id = i;
break;
case 'Menu_Title':
xMenu_Title = i;
break;
case 'Parent':
xParent = i;
break;
case 'URL':
xURL = i;
break;
case 'User_Roles':
xUser_Roles = i;
break;
}
}
// Define the function to filter the menu rows
// Parameters: r - two-dimentional rows array
// p - criterion (the parent menu ID)
// idx - index of needed field
// f - returned filtered array (no need to use in calling statement)
var filterArray = function (r, p, idx, f) {
f = dojo.filter(r, function (item) {
return item[idx] == p;
});
return f;
}
// Define the recurcive function to create the sub menu tree for Menu bar item
// Parameters: parentMenu - the menu to add childs
// parentID - the ID of parent menu to select direct children
// role - current user role
var subMenuFactory = function (parentMenu, parentID, role) {
var i;
var fa = filterArray(rows, parentID, xParent);
var sub;
for (i = 0; i < fa.length; i++) {
if (fa[i][xUser_Roles].indexOf(role) >= 0 || fa[i][xUser_Roles] == 'all') {
if (fa[i][xURL] != '0') { // leaf
url = fa[i][xURL];
parentMenu.addChild(new MenuItem({
dir: 'ltr',
label: fa[i][xMenu_Title],
action: fa[i][xURL],
onClick: function () { me.menuAction(this.action); }
}));
}
else { // DropDown Node
sub = new DropDownMenu({ dir: 'ltr' });
subMenuFactory(sub, fa[i][xMenu_Id], role);
parentMenu.addChild(new MenuSeparator({}));
parentMenu.addChild(new PopupMenuBarItem({
dir: 'ltr',
label: fa[i][xMenu_Title],
popup: sub
}));
}
}
}
}
// Get array of Menu bar items
var filtered = filterArray(rows, 0, xParent);
var pSub;
var user_Role = this.user.Role;
for (i = 0; i < filtered.length; i++) {
if (filtered[i][xUser_Roles].indexOf(user_Role) >= 0 || filtered[i][xUser_Roles]=='all') {
if (filtered[i][xURL] != '0') // leaf
{
pM.addChild(new MenuBarItem({
dir: 'ltr',
label: filtered[i][xMenu_Title],
action: filtered[i][xURL],
onClick: function () { me.menuAction(this.action); }
}));
}
else { // DropDown Node
pSub = new DropDownMenu({ dir: 'ltr' });
subMenuFactory(pSub, filtered[i][xMenu_Id],user_Role);
pM.addChild(new PopupMenuBarItem({
dir: 'ltr',
label: filtered[i][xMenu_Title],
popup: pSub
}));
}
}
}
},
I've found what's the problem. In the required array of define I erroneously import PopupMenubarItem instead of PopupMenuItem. In the function the parameter is named right - PopupMenuItem, but evidently it couldn't help a lot...
Thanks to everyone who tried to help me.
Regards,
Gena

Triggering clearIconTap callback on dynamically created fields

I am creating a simple app using Sencha Touch where I'm dynamically creating container with textfields, textareafields etc. when the user needs to add new container with components. The problem now is when the clear icon on the textareafield is tapped it clears the text, but I would like to know which textareafield has been cleared. Can anyone help me in this please?
This is how I created container .
var childObj2 = {};
childObj2.xtype = 'container';
var type = 'vbox';
var layout = {}
layout.type = type;
childObj1.layout = layout;
var txtarea= {};
txtarea.xtype = 'textareafield';
txtarea.id = "txt51";
txtarea.flex = 3;
txtarea.maxRows = 7;
txtarea.placeHolder = 'Type here';
txtarea.value = value['notes'];
txtarea.inputCls = 'txtareaStyle'
txtarea.clearicontap = "clearText";
How to add clearicontap listener to this?
When you you create a textfield simply add a listener to it for the clearicontap event and that callback will get executed for each of the fields.
For example:
var container = Ext.create('Ext.Container', {});
for (var i=1; i<=3; i++) {
var field = Ext.create('Ext.field.Text', {
id: 'textfieldnumber' + i,
listeners: {
clearicontap: function() {
alert("Tapped clear icon on text field number: " + i + "!");
}
}
});
container.add(field);
}
[EDIT]
I answer the question you make after your edit:
I am using the standard way of creating Sencha components through Ext.create(), and I would suggest you to switch to the same way. It is not clear by the code you posted how those Javascript objects are actually transformed into Ext components. Anyway, they are very likely components configurations, so I guess you could try:
txtarea.listeners = {
clearicontap: function() {
alert("Tapped clear icon on text field");
}
}

How to delete multiple users from a group

Not sure why facebook refered me here but anyhow, let me ask the question. I have a group on facebook with over 4000 members. I want to delete old members that are not active on the group anymore. Is there a way to select multiple users for deletion?
How to get a list of ID's of your facebook group to avoid removal of active users, it's used to reduce as well a group from 10.000 to 5000 members as well as removal of not active members or old members "You will risk removing some few viewers of the group" "remember to open all comments while you browse down the page":
You will need to have Notepad++ for this process:
After you save the HTML. Remove all information before of document:
"div id=contentArea" to
"div id=bottomContent"
to avoid using messenger ID's,
somehow script will run problems if you have ID's by blocked users.
As well as a different example of how to parse as well as text and code out of HTML. And a range of numbers if they are with 2 digits up to 30.
You can try this to purge the list of member_id= and with them along with numbers from 2 to up to 30 digits long. Making sure only numbers and whole "member_id=12456" or "member_id=12" is written to file. Later you can replace out the member_id= with blanking it out. Then copy the whole list to a duplicate scanner or remove duplicates. And have all unique ID's. And then use it in the Java code below.
"This is used to purge all Facebook user ID's by a group out of a single HTML file after you saved it scrolling down the group"
Find: (member_id=\d{2,30})|.
Replace: $1
You should use the "Regular Expression" and ". matches newline" on above code.
Second use the Extended Mode on this mode:
Find: member_id=
Replace: \n
That will make new lines and with an easy way to remove all Fx0 in all lines to manually remove all the extra characters that come in buggy Notepad++
Then you can easily as well then remove all duplicates. Connect all lines into one single space between. The option was to use this tool which aligns the whole text with one space between each ID: https://www.tracemyip.org/tools/remove-duplicate-words-in-text/
As well then again "use Normal option in Notepad++":
Find: "ONE SPACE"
Replace ','
Remember to add ' to beginning and end
Then you can copy the whole line into your java edit and then remove all members who are not active. If you though use a whole scrolled down HTML of a page. ['21','234','124234'] <-- remember right characters from beginning. Extra secure would be to add your ID's to the beginning.
You put your code into this line:
var excludedFbIds = ['1234','11223344']; // make sure each id is a string!
The facebook group removal java code is on the user that as well posted to this solution.
var deleteAllGroupMembers = (function () {
var deleteAllGroupMembers = {};
// the facebook ids of the users that will not be removed.
// IMPORTANT: bobby.leopold.5,LukeBryannNuttTx!
var excludedFbIds = ['1234','11223344']; // make sure each id is a string!
var usersToDeleteQueue = [];
var scriptEnabled = false;
var processing = false;
deleteAllGroupMembers.start = function() {
scriptEnabled = true;
deleteAll();
};
deleteAllGroupMembers.stop = function() {
scriptEnabled = false;
};
function deleteAll() {
if (scriptEnabled) {
queueMembersToDelete();
processQueue();
}
}
function queueMembersToDelete() {
var adminActions = document.getElementsByClassName('adminActions');
console.log(excludedFbIds);
for(var i=0; i<adminActions.length; i++) {
var gearWheelIconDiv = adminActions[i];
var hyperlinksInAdminDialog = gearWheelIconDiv.getElementsByTagName('a');
var fbMemberId = gearWheelIconDiv.parentNode.parentNode.id.replace('member_','');
var fbMemberName = getTextFromElement(gearWheelIconDiv.parentNode.parentNode.getElementsByClassName('fcb')[0]);
if (excludedFbIds.indexOf(fbMemberId) != -1) {
console.log("SKIPPING "+fbMemberName+' ('+fbMemberId+')');
continue;
} else {
usersToDeleteQueue.push({'memberId': fbMemberId, 'gearWheelIconDiv': gearWheelIconDiv});
}
}
}
function processQueue() {
if (!scriptEnabled) {
return;
}
if (usersToDeleteQueue.length > 0) {
removeNext();
setTimeout(function(){
processQueue();
},1000);
} else {
getMore();
}
}
function removeNext() {
if (!scriptEnabled) {
return;
}
if (usersToDeleteQueue.length > 0) {
var nextElement = usersToDeleteQueue.pop();
removeMember(nextElement.memberId, nextElement.gearWheelIconDiv);
}
}
function removeMember(memberId, gearWheelIconDiv) {
if (processing) {
return;
}
var gearWheelHref = gearWheelIconDiv.getElementsByTagName('a')[0];
gearWheelHref.click();
processing = true;
setTimeout(function(){
var popupRef = gearWheelHref.id;
var popupDiv = getElementByAttribute('data-ownerid',popupRef);
var popupLinks = popupDiv.getElementsByTagName('a');
for(var j=0; j<popupLinks.length; j++) {
if (popupLinks[j].getAttribute('href').indexOf('remove.php') !== -1) {
// this is the remove link
popupLinks[j].click();
setTimeout(function(){
var confirmButton = document.getElementsByClassName('layerConfirm uiOverlayButton selected')[0];
var errorDialog = getElementByAttribute('data-reactid','.4.0');
if (confirmButton != null) {
if (canClick(confirmButton)) {
confirmButton.click();
} else {
console.log('This should not happen memberid: '+memberId);
5/0;
console.log(gearWheelIconDiv);
}
}
if (errorDialog != null) {
console.log("Error while removing member "+memberId);
errorDialog.getElementsByClassName('selected layerCancel autofocus')[0].click();
}
processing = false;
},700);
continue;
}
}
},500);
}
function canClick(el) {
return (typeof el != 'undefined') && (typeof el.click != 'undefined');
}
function getMore() {
processing = true;
more = document.getElementsByClassName("pam uiBoxLightblue uiMorePagerPrimary");
if (typeof more != 'undefined' && canClick(more[0])) {
more[0].click();
setTimeout(function(){
deleteAll();
processing = false;
}, 2000);
} else {
deleteAllGroupMembers.stop();
}
}
function getTextFromElement(element) {
var text = element.textContent;
return text;
}
function getElementByAttribute(attr, value, root) {
root = root || document.body;
if(root.hasAttribute(attr) && root.getAttribute(attr) == value) {
return root;
}
var children = root.children,
element;
for(var i = children.length; i--; ) {
element = getElementByAttribute(attr, value, children[i]);
if(element) {
return element;
}
}
return null;
}
return deleteAllGroupMembers;
})();
deleteAllGroupMembers.start();
// stop the script by entering this in the console: deleteAllGroupMembers.stop();
Use this in Chrome or Firefox Javascript control panel.

Dropdowns not rendered when override object.cshtml MVC4

My actual problem was mentioned here.
Hide property of model in dynamic view
To solve the problem, I have overrided object.cshtml as mentioned in the answer.
However, when I did this, the dropdowns that I am rendering using UIHints are not working.
In place of dropdown, just False, False False (the no.of Falses are equal to number of list items I have in my viewdata) are displayed.
I am not sure what is happening here, can somebody advise what is going on?
in my controller:
ViewData["PartyRoleTypeId"] = (IEnumerable<SelectListItem>)PartyRoleTypeRepo.All()
.ToList()
.Select(p => new SelectListItem { Value = p.PartyRoleTypeId.ToString(), Text = p.Caption, Selected = p.PartyRoleTypeId == obj.PartyRoleTypeId });
ViewData["PartyId"] = (IEnumerable<SelectListItem>)PartyRepo.All()
.ToList()
.Select(p => new SelectListItem { Value = p.PartyId.ToString(), Text = p.Organization.Caption, Selected = p.PartyId == obj.PartyId });
My dropdown edit template in shared/editortemplates/DropDownList.cshtml
#{
var fieldName = ViewData.ModelMetadata.PropertyName;
}
#Html.DropDownList("",(IEnumerable<SelectListItem>)ViewData[fieldName], "Choose..." , new { #class ="combo"})
object.cshtml
#functions
{
bool ShouldShow (ModelMetadata metadata)
{
return metadata.ShowForEdit
&& metadata.ModelType != typeof(System.Data.EntityState)
&& !metadata.IsComplexType
&& !ViewData.TemplateInfo.Visited(metadata);
}
}
#if (ViewData.TemplateInfo.TemplateDepth > 1)
{
if (Model == null)
{
#ViewData.ModelMetadata.NullDisplayText
}
else
{
#ViewData.ModelMetadata.SimpleDisplayText
}
}
else
{
//ViewData.Clear();
foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => ShouldShow(pm)))
{
if (prop.HideSurroundingHtml)
{
#Html.Editor(prop.PropertyName)
}
else if (prop.DisplayName == "Id")
{
<div></div>
}
else if (!string.IsNullOrEmpty(Html.Label(prop.PropertyName).ToHtmlString()))
{
<div class="editor-label">#Html.Label(prop.PropertyName)</div>
}
<div class="editor-field">#Html.Editor(prop.PropertyName) #Html.ValidationMessage(prop.PropertyName, "")</div>
}
}
There is some problem with keeping my dropdown values in ViewData or ViewBag.
When I use these, for prartyroletypeid it is not recognizing UIHint dropdownlist.cshtml. It is still referring to object.cshtml.
Instead I kept the dropdown data in TempData and everything is working fine.
But not sure, if I can use TempData in this context.
Any ideas???