How to create dynamic instances of JQueryTE text editor - javascript

I am attempting to create a small program that incorporates dynamically created instances of this editor.
I have it working except for the ability to create a button that opens/closes the editor.
jsFiddle of what I've got so far.
"use strict";
$(document).ready(function() {
var createPad = $("#createPad").click(function () {
var body = document.getElementById("body");
var editorNumberCounter = 1;
var toggleOnOffCounter= 1;
var editorName = '.'+ (editorNumberCounter++);
var status = document.createElement('div');
status.className = "status";
status.id = "status";
var editorName= document.createElement('span');
editorName.className = "status";
editorName.id = "status";
$(body.appendChild(status));
$(body.appendChild(editorName));
var toggle = status.id + toggleOnOffCounter++;
$(editorName).jqte();
// settings of status
var jqteStatus = true;
$(toggle).click(function()
{
jqteStatus = jqteStatus ? false : true;
$(editorName).jqte({toggle : jqteStatus})
});
});
});

I made up some changes to your code an now seems to work.
I try to explain them point by point:
variabiles editorNumberCounter and toggleOnOffCounter must be globally scoped or you lose the incremented value
ID of elements (dynamically created or not) MUST be unique, so I create the div and span element considering the counter
for dynamically created elements you must use the bind method or the event will not be bind
the toggle property not exist! You must use the status property
the element onto JQTE is binded is get as next element after the clicked element
Code:
var editorNumberCounter = 0;
var toggleOnOffCounter = 0;
$(document).ready(function () {
var createPad = $("#createPad").click(function () {
var body = document.getElementById("body");
var editorName = '.' + editorNumberCounter++;
toggleOnOffCounter++;
var status = document.createElement('div');
status.className = "status";
status.id = "div_status" + editorNumberCounter;
var editorName = document.createElement('span');
editorName.className = "status";
editorName.id = "span_status" + editorNumberCounter;
$(body.appendChild(status));
$(body.appendChild(editorName));
$(editorName).jqte();
// settings of status
var jqteStatus = true;
$("#div_status" + editorNumberCounter).bind("click",function () {
jqteStatus = jqteStatus ? false : true;
$(this).next().jqte({
status: jqteStatus
})
});
});
});
Here is a working fiddle: http://jsfiddle.net/IrvinDominin/UfhNQ/14/

Related

swap the Multiple Video Html elements before Removing

how to swap the elements before Removing them without the use of a clone using jquery
I created the video call app for using picture in picture mode that was working properly but I have a small issue when I click to swap the video that working properly, after swapping when I want to remove some video they are not working properly.
JsFile
/* swaping the videoElement */
function initVideoSwapping() {
// check if there is an element first
if ($('.video-list .videoWrap').length > 0 && $('.mainVideo').length > 0) {
$('.video-list .videoWrap').on('click', function () {
/* stopEvent Propogation */
var $this = $(this);
console.log($this)
$this.data('clicked', true);
initRemoveSwap()
var IsadminTrue = getDataFromQueryString()
if (IsadminTrue.isadmin) {
var $StopthisDrop = $(this).find('#DropDown')[0];
$StopthisDrop.addEventListener('click', (e) => {
e.stopImmediatePropagation()
})
var $StopthisBtn = $(this).find('button')[0];
$StopthisBtn.addEventListener('click', (e) => {
e.stopImmediatePropagation()
})
}
// name
var $thisName = $(this).find('span')[0]
var $mainName = $('.main-videoWrap').find('span')[0]
// dropdown
var $thisBtn = $(this).find('button')[0];
var $mainbtn = $('.main-videoWrap').find('button')[0];
var $thisUlElement = $(this).find('ul')[0];
var $mainUlElement = $('.main-videoWrap').find('ul')[0];
// video
var $thisVideo = $(this).find('video')[0];
var $mainVideo = $('.main-videoWrap').find('video')[0];
swapNodes($thisVideo, $mainVideo, $thisName, $mainName, $thisBtn, $mainbtn, IsadminTrue, $thisUlElement, $mainUlElement);
});
}
}
function swapNodes(thisVideo, mainVideo, thisName, mainName, thisBtn, mainbtn, thisUlelement, mainUlElement) {
var thisVideoparent = thisVideo.parentNode;
var asibling = thisVideo.nextSibling === mainVideo ? thisVideo : thisVideo.nextSibling;
mainVideo.parentNode.insertBefore(thisVideo, mainVideo);
thisVideoparent.insertBefore(mainVideo, asibling);
// Name Change
var thisNameParent = thisName.parentNode;
var Namesiblings = thisName.nextSibling === mainName ? thisName : thisName.nextSibling;
mainName.parentNode.insertBefore(thisName, mainName);
thisNameParent.insertBefore(mainName, Namesiblings);
// dropdown change
var BtnParanet = thisBtn.parentNode;
var Btniblings = thisBtn.nextSibling === mainbtn ? thisBtn : thisBtn.nextSibling;
mainbtn.parentNode.insertBefore(thisBtn, mainbtn);
BtnParanet.insertBefore(mainbtn, Btniblings);
// ulElement Change
var UlParanet = thisUlelement.parentNode;
var ULSiblings = thisUlelement.nextSibling === mainUlElement ? thisUlelement : thisUlelement.nextSibling;
mainUlElement.parentNode.insertBefore(thisUlelement, mainUlElement);
UlParanet.insertBefore(mainUlElement, ULSiblings);
}
var asibling = thisVideo.nextSibling === mainVideo ? thisVideo : thisVideo.nextSibling;
mainVideo.parentNode.insertBefore(thisVideo, mainVideo);
thisVideoparent.insertBefore(mainVideo, asibling);
// Name Change
var thisNameParent = thisName.parentNode;
var Namesiblings = thisName.nextSibling === mainName ? thisName : thisName.nextSibling;
mainName.parentNode.insertBefore(thisName, mainName);
thisNameParent.insertBefore(mainName, Namesiblings);
// if (IsadminTrue.isadmin) {
var BtnParanet = thisBtn.parentNode;
var Btniblings = thisBtn.nextSibling === mainbtn ? thisBtn : thisBtn.nextSibling;
mainbtn.parentNode.insertBefore(thisBtn, mainbtn);
BtnParanet.insertBefore(mainbtn, Btniblings);
// ulElement Change
var UlParanet = thisUlelement.parentNode;
var ULSiblings = thisUlelement.nextSibling === mainUlElement ? thisUlelement : thisUlelement.nextSibling;
mainUlElement.parentNode.insertBefore(thisUlelement, mainUlElement);
UlParanet.insertBefore(mainUlElement, ULSiblings);
// }
}}
My Last Try was
function initRemoveSwap() {
var IsadminTrue = getDataFromQueryString()
if (IsadminTrue.isadmin) {
$('.video-list .videoWrap').on('remove', function () {
var $thisVideo = $(this).find('video')[0];
var $mainVideo = $('.main-videoWrap').find('video')[0];
// name
var $thisName = $(this).find('span')[0]
var $mainName = $('.main-videoWrap').find('span')[0]
// dropdown
var $thisBtn = $(this).find('button')[0];
var $mainbtn = $('.main-videoWrap').find('button')[0];
var $thisUlElement = $(this).find('ul')[0];
var $mainUlElement = $('.main-videoWrap').find('ul')[0];
RemoveswapNodes($mainVideo, $thisVideo, $thisName, $mainName, $thisBtn, $mainbtn, IsadminTrue, $thisUlElement, $mainUlElement);
})
}
function RemoveswapNodes(mainVideo, thisVideo, thisName, mainName, thisBtn, mainbtn, IsadminTrue, thisUlelement, mainUlElement) {
// videoChange
var thisVideoparent = thisVideo.parentNode;
var asibling = thisVideo.nextSibling === mainVideo ? thisVideo : thisVideo.nextSibling;
mainVideo.parentNode.insertBefore(thisVideo, mainVideo);
thisVideoparent.insertBefore(mainVideo, asibling);
// Name Change
var thisNameParent = thisName.parentNode;
var Namesiblings = thisName.nextSibling === mainName ? thisName : thisName.nextSibling;
mainName.parentNode.insertBefore(thisName, mainName);
thisNameParent.insertBefore(mainName, Namesiblings);
// if (IsadminTrue.isadmin) {
var BtnParanet = thisBtn.parentNode;
var Btniblings = thisBtn.nextSibling === mainbtn ? thisBtn : thisBtn.nextSibling;
mainbtn.parentNode.insertBefore(thisBtn, mainbtn);
BtnParanet.insertBefore(mainbtn, Btniblings);
// ulElement Change
var UlParanet = thisUlelement.parentNode;
var ULSiblings = thisUlelement.nextSibling === mainUlElement ? thisUlelement : thisUlelement.nextSibling;
mainUlElement.parentNode.insertBefore(thisUlelement, mainUlElement);
UlParanet.insertBefore(mainUlElement, ULSiblings);
// }
}
}
window.addEventListener('click', initVideoSwapping, false)
I've tried a lot of different ways to change items. I've tried with replaceWith(), before(), and after() but nothing worked.
NOTE: I've already written a function which displays the correct up / down DIVs. So the first and last one can only moved in one direction. That's already solved. I also can't use any kind of existing jQuery plugins.
Kindly Help to how to solve this issue!

How to have a div open by a button closed by clicking off when there are multiple buttons?

I have several buttons on my site that call a script to open the content into full screen and I also want to be able to click off the created div to close it. This works but after opening one container, which is deleted after, my program produces errors trying to click another button.
function closeDiv(evt) {
const maindiv = document.getElementById('div3');
let targetElement = evt.target;
do {
if (targetElement == maindiv.childNodes[1]) {
return;
}
targetElement = targetElement.parentNode;
} while (targetElement);
var viewpost = maindiv.childNodes[1];
viewpost.parentNode.removeChild(viewpost);
maindiv.classList.remove('viewcontainer');
};
function buttonClick(button) {
var div = button.parentElement.parentElement;
var clone = div.cloneNode(true);
var element = div.childNodes;
var username = element[1].innerText;
var title = element[7].innerText;
var contenttext = div.childNodes[3].value;
var clone = document.createElement('div');
clone.classList.add('viewcontainercon');
var viewuser = document.createElement('p');
viewuser.classList.add('viewcontaineruser');
var text = document.createTextNode(username);
viewuser.appendChild(text);
clone.appendChild(viewuser)
var viewtitle = document.createElement('p');
viewtitle.classList.add('viewcontainertitle');
var text = document.createTextNode(title);
viewtitle.appendChild(text);
clone.appendChild(viewtitle);
var viewcontent = document.createElement('p');
viewcontent.classList.add('viewcontainercontent');
var text = document.createTextNode(contenttext);
viewcontent.appendChild(text);
clone.appendChild(viewcontent);
document.getElementById('div3').classList.add('viewcontainer');
document.getElementById('div3').appendChild(clone);
document.addEventListener("click", function(event){
var isClickInside = button.contains(event.target);
if (!isClickInside) {
closeDiv(event);
}
});
}
The error is specifically `viewpost is undefined' in the closeDiv() function, which is strange since that shouldn't be called until after the click. Any ideas?

Uncaught TypeError: Cannot set property 'onfocus' of null

I am trying to learn JavaScript and I'm building this basic tutorial. In trying to demonstrate onfocus and onblur, I get this error message in my JavaScript console: Uncaught TypeError: cannot set property 'onfocus' of null.
Here is my code. I am new to learning JavaScript and could really use some help.
//alert("Hello, world!");
// this is a JavaScript alert button
//
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro to JavaScript! YAY!");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers(); // This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White-Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage, 5000);
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
If it's giving you that error, then it means that document.getElementById("email") evaluates to null, which means that no element exists with the id email.
That's all I can tell you without seeing the HTML that this JS is connected to.

Add a colspan to a JS generated cell

I have some JavaScript that creates a row in a table and adds cells to it. I need to put an colspan=2 on the second cell added (A.K.A the select cell), but I can't figure out the best way to do this with the least change in the code because this affects a entire page of more code. Suggestions? (table id=table5 class=mytable)
if(fltgrid)
{
var fltrow = t.insertRow(0); //adds filter row
fltrow.className = "fltrow";
for(var i=0; i<n; i++)// this loop adds filters
{
var fltcell = fltrow.insertCell(i);
//fltcell.noWrap = true;
i==n-1 && displayBtn==true ? inpclass = "flt_s" : inpclass = "flt";
if(f==undefined || f["col_"+i]==undefined || f["col_"+i]=="none")
{
var inptype;
(f==undefined || f["col_"+i]==undefined) ? inptype="text" : inptype="hidden";//show/hide input
var inp = createElm( "input",["id","flt"+i+"_"+id],["type",inptype],["class",inpclass] );
inp.className = inpclass;// for ie<=6
fltcell.appendChild(inp);
if(enterkey) inp.onkeypress = DetectKey;
}
else if(f["col_"+i]=="select")
{
var slc = createElm( "select",["id","flt"+i+"_"+id],["class",inpclass] );
slc.className = inpclass;// for ie<=6
fltcell.appendChild(slc);
PopulateOptions(id,i);
if(displayPaging)//stores arguments for GroupByPage() fn
{
var args = new Array();
args.push(id); args.push(i); args.push(n);
args.push(display_allText); args.push(sort_slc); args.push(displayPaging);
SlcArgs.push(args);
}
if(enterkey) slc.onkeypress = DetectKey;
if(on_slcChange)
{
(!modfilter_fn) ? slc.onchange = function(){ Filter(id); } : slc.onchange = f["mod_filter_fn"];
}
}
if(i==n-1 && displayBtn==true)// this adds button
{
var btn = createElm(
"input",
["id","btn"+i+"_"+id],["type","button"],
["value",btntext],["class","btnflt"]
);
btn.className = "btnflt";
fltcell.appendChild(btn);
(!modfilter_fn) ? btn.onclick = function(){ Filter(id); } : btn.onclick = f["mod_filter_fn"];
}//if
}// for i
}//if fltgrid
If I understand you correctly, you can change the code block in the else if to the following:
var slc = createElm( "select",["id","flt"+i+"_"+id],["class",inpclass] );
slc.className = inpclass;// for ie<=6
fltcell.appendChild(slc);
fltcell.setAttribute("colspan",2);
PopulateOptions(id,i);

Button handling and layer visibility in Greasemonkey

I have a Greasemonkey script that I've been building for a game. The idea is to have info about the game in a div that will pop up when a button (which is added by my script) on the page is clicked.
I'm using z-index because when I just display the div over the top of the game screen, some of the images show through. So, basically what I need to do is change the z-index of my div based on the value of a variable and/or button click. However, I cannot get my div to come to the front when I click my button.
Here's what I have so far:
// ==UserScript==
// #name Test Script
// #namespace http://therealmsbeyond.com/
// #description Test
// #include an_include.js
// #include another_include.js
// #require json.js
// ==/UserScript==
var VERSION = 1;
var WEBSITEURL = 'http://therealmsbeyond.com/';
var SCRIPTNAME = 'Test';
var SENDINFODELAY = 600000;
var UPDATEDELAY = 604800000;
var ZINDEX_UNDER = -100;
var ZINDEX_OVER = 111111;
var Options = {
'mapVisible' : false,
'showHostile' : false,
'showAlliance' : false,
'showBookmarks' : false
}
function custom_setValue(k,v){
GM_setValue(k,v);
}
function custom_getValue(k,dv){
return(GM_getValue(k,dv));
}
function custom_deleteValue(k){
GM_deleteValue(k);
}
function getSavedInfo(){
return(custom_getValue('ajaxparams',null));
}
function getSavedServerId(){
return(custom_getValue('sid'));
}
var e = document.createElement('div');
var idAttr = document.createAttribute('id');
var styleAttr = document.createAttribute('style');
idAttr.nodeValue = 'shadow_map_container';
styleAttr.nodeValue = 'background-color:white;top:150px;left:75px;position:absolute;height:600px;width:600px;';
e.setAttributeNode(idAttr);
e.setAttributeNode(styleAttr);
var c = '<strong>This is the map window.</strong>';
e.innerHTML = c;
document.body.appendChild(e);
if(Options.mapVisible == true)
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_OVER;
}
else
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_UNDER;
}
function showHide()
{
if(Options.mapVisible == true)
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_UNDER;
Options.mapVisible = false;
}
else
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_OVER;
Options.mapVisible = true;
}
}
var btnStr = '<a class="navTab" target="_top" onclick="showHide();return false;" href="javascript:void(0)"><span>Shadow Mapper</span></a>';
var myNavContainer = document.getElementById('main_engagement_tabs');
var inner = myNavContainer.innerHTML;
var newStr = btnStr + inner;
myNavContainer.innerHTML = newStr;
This is not a z-index problem, it's a coding style and event-listener problem.
You cannot activate a button that way in a Greasemonkey script. showHide() resides in the GM sandbox, the page's JS cannot reach it from an onclick.
(One more, of many, reasons why inline JS should be avoided.)
In this example, you would activate the link like so:
function showHide()
{
if(Options.mapVisible == true)
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_UNDER;
Options.mapVisible = false;
}
else
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_OVER;
Options.mapVisible = true;
}
return false;
}
var btnStr = '<a class="navTab" target="_top"><span>Shadow Mapper</span></a>';
var myNavContainer = document.getElementById('main_engagement_tabs');
var inner = myNavContainer.innerHTML;
var newStr = btnStr + inner;
myNavContainer.innerHTML = newStr;
var btn = document.querySelector (".main_engagement_tabs > a.navTab");
btn.addEventListener ("click", showHide, true);

Categories

Resources