Keep javascript within new javascript element - javascript

I am developing a webpage but I came into some trouble with some javascript code.
I am using the Nicedit as WYSIWYG for textareas, which, as stated in its main page, is as easy as copy/paste this 2 lines anywhere in my web page:
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script>
That's working great with the default textareas of the page. The problem is that I also have this javascript to add more textareas:
function addchapter()
{
if (num_chapter < 10)
{
var num=num_chapter+1;
document.getElementById('chapters').innerHTML += "<h3>Chapter " + num + "</h3> Title: <input type='text' name='titlechapter_" + num + "'><br>Content:<textarea name='chapter_" + num + "'></textarea>";
}
else if (num_chapter == 10)
{
document.getElementById('chapters').innerHTML += "<br />Maximum is 10 chapters.";
}
num_chapter += 1;
}
So when I add a textarea through javascript, it doesn't have the proper style; it's not implementing Nicedit. The thing is that the textareas are all standard, so there's no difference between the code in both cases. I don't know too much of javascript but I think that the problem might be that the Nicedit code runs ONCE when the page loads, and that's it. Any idea of how to make it run when the page loads (<= already done) AND when the addchapter function is run?
The relevant HTML bit is this:
<div id="chapters">
</div>
<button type="button" onclick="addchapter()"> Add chapter </button>
My page where you can see the odd behaviour is this (broken link), under Chapter 1 you see the 'Add chapter' button.
Thank you all so much.
EDIT 1, Error console output:
When the page loads it throws this:
"GET http://js.nicedit.com/nicEditIcons-latest.gif
bkClass.extend.getStylenicEdit-latest.js:8
bkClass.extend.constructnicEdit-latest.js:38
AnicEdit-latest.js:8
bkClass.extend.addInstancenicEdit-latest.js:37
bkClass.extend.panelInstancenicEdit-latest.js:37
nicEditors.allTextAreasnicEdit-latest.js:37
bkLib.domLoaded"
When I add a new chapter:
"Uncaught TypeError: Object #<bkClass> has no method 'removeInstance'
bkClass.extend.checkReplacenicEdit-latest.js:37
bkClass.extend.panelInstancenicEdit-latest.js:37
nicEditors.allTextAreasnicEdit-latest.js:37
(anonymous function)/file/new/:112
onclick"

You have to assign a unique ID to the text fields you add to the page. To convert it into an editor you can then call;
nicEditors.findEditor(editorID);
Or you can call nicEditors.allTextAreas() again. But I'm not sure if that will remove the existing content from the editors that already exist.
Source: The API.

You can add try{}catch(e){} block to your code
jQuery('.js-control-des').each(function () {
var index = jQuery(this).attr('lang');
var editor = jQuery(this).find('textarea');
var editor_id = editor.attr('id');
var editor_loaded = editor.attr('rel');
if (editor_loaded == undefined || editor_loaded != null || editor_loaded == 0) {
var editor_new_width = parseFloat(editor.css('min-width')) + 7 + 'px';
editor.css({
width: editor_new_width,
'max-width': editor_new_width,
'min-width': editor_new_width
});
try {
new nicEditor({maxHeight: 300}).panelInstance(editor_id);
jQuery(this).attr('rel', 'editor-loaded');
jQuery(this).find('.nicEdit-main').attr('data-index', index).keyup(function (e) {
if (vnLineUcp.editorKeyUp(jQuery(this)) == false) {
return false;
}
});
} catch (e) {
}
}
});

Related

AJAX based search returning page information

I found the source of the error but do not know how to fix it. I'm using codeigniter and I'm trying to make a textbox with search results showing under it to help the user find what they are looking for. Think similar to google's search. When I make the AJAX call, it's returning everything on the webpage as well as the search results.
Example of issue: https://gyazo.com/244ae8f3835233a2690512cebd65876d
That textbox within the div should not be there as well as the white space. Using inspect element I realized the white spaces are my links to my CSS and JS pages. Then there's the textbox which is from my view.
I believe the issue lies within my JS.
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
}
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = encodeURI(document.getElementById('txtSearch').value);
searchReq.open("GET", '?search=' + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}
//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('txtSearch').value = value;
document.getElementById('search_suggest').innerHTML = '';
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
var ss = document.getElementById('search_suggest');
ss.innerHTML = '';
var str = searchReq.responseText.split("\n");
for (i = 0; i < str.length - 1; i++) {
var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
suggest += 'onmouseout="javascript:suggestOut(this);" ';
suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
suggest += 'class="suggest_link">' + str[i] + '</div>';
ss.innerHTML += suggest;
}
}
}
More specifically the getXmlHttpRequestObject function. it is returning the entire page including my header and footer. I don't believe any more info is needed but if anyone feels that way, I'll supply the view and controller.
https://gyazo.com/d0c43326191a4b09cc4b1d85d67a1bf6
This image shows the console and how the response and response text are the entire page instead of just the results.
Your call to the view method is loading the header view, the suggest view and the footer view while your suggest model is echoing the data that you're after.
You could just remove the line $this->view("suggest"); and your suggestions will be echoed.
This isn't great though. I would pass the titles back to the controller from the model then create a new controller method that outputs the data in a structured way (probably JSON).

Delay Display of Text in Qualtrics using Javascript

(This is related to the unanswered question https://stackoverflow.com/questions/26745762/delaying-presentation-of-text-in-qualtrics)
I am working on a Qualtrics survey. I want to delay some text (say, text) being displayed - it should be hidden for 5 seconds, then display.
I found a resource here - Javascript for Qualtrics - that I can't get to work.
Drawing from this example, I try to replicate it by delaying the display of a photo. I do this to see if I can get this working before I go on to delaying the display of text as opposed to a photo.
In the HTML part, I put:
Time: <span id="time1">30</span><br>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/%C3%81guila_calva.jpg/1280px-%C3%81guila_calva.jpg" style="width: 133px; height: 115px;" class='pic1' />
In the Javascript part, I have:
started = false;
function countDown1() {
if (!started)
started = true;
else {
var value1 = parseInt($('time1').innerHTML);
$('time1').innerHTML = value1 - 1;
if (value1 == 26) {
var styling1 = document.getElementsByClassName('pic1')[0];
styling1.style.display = "none";
}
}
setTimeout(countDown1, 1000);
}
Event.observe(window, 'load', countDown1);
For some reason, nothing happens at all with the timer or the photo.
Do I need to wrap the above Javascript in:
Qualtrics.SurveyEngine.addOnload(function()
{
});
I tried this as well, but no change.
So I really have two questions. 1. How do I modify the above code to get it working. And 2. How do I modify the working version of the code to display text after a certain amount of time?
You're making it more complex than need be.
Here is example html for the question:
This is a question. <span id="hiddentext" style="display:none">This text
will display after five seconds.</span>
Here is the javascript for the question:
Qualtrics.SurveyEngine.addOnload(function()
{
setTimeout("$('hiddentext').style.display = 'inline'",5000);
});
This hides the radiobuttons or Choices in a multiple choice question for 2 seconds. If you need to hide the next button as well you can add a Timing question from the ones already provided in Qualtrics and set it to "Enable submit after (seconds)".
Qualtrics.SurveyEngine.addOnload(function() {
var QID = this.questionId;
console.log(QID);
for (var i = 1; i < 4; i++) {
document.getElementById( QID + "-" + i + "-label" ).style.display="none";
}
(function(delay_container){
for (var i = 1 ; i < 4 ; i ++){
document.getElementById(QID + "-" + i + "-label").style.display="block";
}
}).delay(2,this.questionContainer);
});
Let's say you have two sentences that are two separate Descriptive text boxes. And you want the second box to appear some seconds after the first. The following worked for me when assigned for the second box. The same code works for following boxes as well. You can again put a Timing question at the end of the page to hide Next button.
Qualtrics.SurveyEngine.addOnload(function() {
var QID = this.questionId;
console.log(QID);
for (var i = 1; i < 4; i++) {
document.getElementById( QID).style.display="none";
}
(function(delay_container){
for (var i = 1 ; i < 4 ; i ++){
document.getElementById(QID).style.display="block";
}
}).delay(2,this.questionContainer);
});

jQuery - removing an alert stop code from working

The code below works, but there is an issue with it.
That issue is that unless the alert(this.href); - (about line 11) is in the code the following function does not work.
//There are pages which make up 2 chapters in this content
//We shall attempt to grab all the links from these pages
var c;
var chapters = new Array();
chapters[0] = "original/html/0/ID0EFJAE.html";
//Loop through each page of links
$.each(chapters, function(key, value) {
$("#theContent").append("<div class='chapterindex" + key + "'>working</div>");
$(".chapterindex" + key).load(value + " .content");
alert(this.href);
$(".chapterindex" + key + " div.link a").each(function(intIndex) {
alert(".chapterindex" + key);
});
});
If I take the first alert out of line 11 then the last alert doesn't fire. What am I doing wrong?
The delay that the alert is causing is allowing the data in your load call to load. I suspect that when you remove the alert the data does not load in time.
Try using a callback with your load call, something like (code not tested) -
$(".chapterindex" + key).load(value + " .content",function () {
$(".chapterindex" + key + " div.link a").each(function(intIndex) {
alert(".chapterindex" + key);
});
});
The first alert is probably giving the load function enough time to finish so when you take it out the load function is not done when its trying to fire your second alert.

Send variables to javascript(jquery) function

I wont to be able to send a variable to a JavaScript function when I click on a link but for some reason I cant find anywhere on how to do it on the internet.
Here is the function at the top of my page:
<script>
$(document).ready(function(){
$('[name=updateInterface]').click(function() {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h= &v= ");
});
});
</script>
As you can see I need the variable to be placed after the "h=" and "v=" parts.
Here is the link to activate the function in my page:
<img src="images/map/invisible.png" border="0" />
Variables from where? It's easy enough:
var h = 20;
var v = 40;
$(function() {
$('[name=updateInterface]').click(function() {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" +
encodeURIComponent(h) + "&v=" + enocdeURICompoennt(v));
});
});
Just make sure you escape them with encodeURIComponent().
You can of course get them from anywhere like:
<input type="text" id="txth">
<input type="text" id="txth">
and then:
var h = $("#txth").val();
var v = $("#txtv").val();
Edit: Ok, from your comments I gather you want to send the information from the server back to the client so the client can send it back. The first is to do your click handler in a non-jquery kind of way:
Click me
with:
function handle_click(h, v) {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" +
encodeURIComponent(h) + "&v=" + enocdeURICompoennt(v));
}
That's probably the easiest solution. If you want to stick with jquery click handlers you can always embed this information in an attribute or a hidden element. For example:
<div class="special-h">12</div><div class="special-v">34</div>Click me
with CSS:
a.special div { display: none; }
and:
$(function() {
$("a.special").click(function() {
var h = $(this).children("special-h").text();
var v = $(this).children("special-v").text();
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" +
encodeURIComponent(h) + "&v=" + enocdeURICompoennt(v));
});
});
There are many variations on this theme.
Lastly, I'll point out that I would advise you not to do attribute lookup selectors where you can possibly avoid it. Give the anchor a class and/or ID and use one of those to assign the event handler. Also use a selector like "a.special" over ".special" too (for performance reasons).
Do you mean appending them into the URL string?
<script>
$(document).ready(function(){
$('[name=updateInterface]').click(function() {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" + h + "&v=" + v);
});
});
</script>
This assumes you have the variables h and v defined elsewhere in your script.

RadEditor scrolls to top after pasting the contents

I am using Telerik RadEditor.
The issue:
On pasting the content into the Telerik Radeditor, the editor is getting scrolled to top. So, I searched the internet and also Telerik forums, but no luck. Finally, I worked on the following code with fix.
Code for RadEditor Server-Side Control:
<telerik:RadEditor
ID="E"
runat="server"
Width="100%"
AllowScripts="true"
AllowPaging="true"
EnableResize="false"
NewLineMode="P"
OnClientLoad="OnClientLoad"
OnClientModeChange="E_OnClientModeChanged"
EditModes="Design,Html"
StripFormattingOptions="Span,MsWordRemoveAll,CSS,Font,ConvertWordLists"
OnClientPasteHtml="radEditorControl_OnClientPasteHtml"
OnClientSelectionChange="OnClientSelectionChange">
</telerik:RadEditor>
Below is the Javascript Code with fix:
//Event on pasting the content into the RadEditor. Fixing the scrolling issue on pasting the content.
var isPasted = false;
function radEditorControl_OnClientPasteHtml(editor, args) {
if (editor != undefined)
isPasted = true;
}
function OnClientSelectionChange(editor, args) {
if (isPasted != undefined && isPasted == true && editor != undefined) {
isPasted = false;
editor.setFocus();
var iframeElement = editor._contentAreaElement; // the DOM element for the iframe;
if (iframeElement) {
//Get the iFrame cursor position.
var _focusNode = iframeElement.contentWindow.getSelection().focusNode;
if (_focusNode != undefined) {
//Focus node is not an element, get the previous element sibling
if (_focusNode.nodeType != 1) {
if (_focusNode.previousElementSibling != undefined)
_focusNode = _focusNode.previousElementSibling;
else
_focusNode = _focusNode.parentNode;
}
//Insert a div near focusNode(cursor) of the iFrame contentWindow.
var timeStamp = new Date().getUTCMilliseconds();
var _id = "scrollArea_" + timeStamp;
var focusElement = jQuery('<input type="text" id="' + _id + '" name="' + _id + '" onfocus="alert();" />').insertAfter(_focusNode)[0];
setTimeout(function () {
if (focusElement != undefined) {
focusElement.focus({ preventScroll: true });
focusElement.select();
var range = editor.getSelection().getRange(true); //returns an object that represents a restore point.
editor.getSelection().selectRange(range);
if (range != undefined && range.collapse !=undefined)
range.collapse(true);
jQuery(focusElement).replaceWith("");
}
}, 50);
}
}
}
}
The above code is working in IE and Chrome, but not in Firefox as focus() is not getting triggered for the input element which I am binding.
Please let me know if there is any other way for resolving the scroll issue on paste in RadEditor.
I am aware of such a problem within the older versions of RadEditor. My advice is to try the latest version which you can test at https://demos.telerik.com/aspnet-ajax/editor/examples/overview/defaultcs.aspx. If the problem still persists please drop us a line in the Telerik AJAX forums or via the support ticketing system and we will look deeper into it.

Categories

Resources