Dynamically adding jquery into div - javascript

Apologies, I know there are a number of questions along the same lines and they've helped me a lot but I'm still falling at the final hurdle.
I'm trying to dynamically add some jQuery into a div using this:
function displayPage(position,page){
// position arrives looking something like '#pageW20' - ignore quotes
// page arrives looking something like 'pages/benefits.html' - ignore quotes
var pos = position.substring(1); // New variable without the '#' that appears in the first character of position
var myDiv = document.getElementById(pos); // Find the div, typically equates to a div id similar to 'pageW20'
var str = "<script type='text/javascript'>";
/* Build the script which typically looks like this:-
<script type='text/javascript'> $( "#pageB15" ).load( "pages/benefits.html", function(){openLetter()}); </script>
*/
str += '$( ' + '"' + position + '"' +' ).load(' + page + ', function(){openLetter()})';
str += '<';
str += '/script>';
alert(str); // Works to here, alert churns out expected output.
//$('"' + position + '"').append(str); // Tried this, end up with syntax error
myDiv.appendChild(str); // This gives Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
}
The last two lines show the errors I'm getting trying 2 different methods. Any clues.
Thanks appreciate your interest.
Update: Here's what I get in my console at the alert() stage which is what I was hoping for -
<script type='text/javascript'>$( "#pageW20" ).load("pages/work.html", function(){openLetter()})</script>
Update: Now solved, thanks #gaetano. My code now looks like:
function displayPage(position,page){
var pos = position.substring(1);
var myDiv = document.getElementById(pos);
myDiv.innerHTML=""; // Remove existing div content
/* Build the script which typically looks like this:-
<script type='text/javascript'> $( "#pageB15" ).load( "pages/benefits.html", function(){openLetter()}); </script>
*/
var str = '$( ' + '"' + position + '"' +' ).load(' + page + ', function(){openLetter()});';
console.log(str);
var s = document.createElement('script');
s.type = 'text/javascript';
s.text = str;
myDiv.appendChild(s);
}

I cannot understand why you are trying to create and append a script on the fly like described in the comments.
The error you get is:
myDiv.appendChild(str);
But appendChild requires as first parameter a node.
So if you need to continue in this direction you have to create a script node element and after you can append it to the html like in my example:
function displayPage(position, page) {
var pos = position.substring(1); // New variable without the '#' that appears in the first character of position
var myDiv = document.getElementById(pos); // Find the div, typically equates to a div id similar to 'pageW20'
var str = '$( ' + '"' + position + '"' + ' ).load("' + page + '", function(){openLetter()})';
var s = document.createElement('script');
s.type = 'text/javascript';
s.text = str;
myDiv.appendChild(s);
}
displayPage('_XXX', 'page');
console.log(document.getElementById('XXX').outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="XXX"></div>

The str variable you're passing isn't a Node, it's a String. Try first using:
var line = document.createElement("p");
line.innerHTML = str;
myDiv.appendChild(line);

Related

How to concatenate and pass parameters values in html using jQuery

I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

Eval multiple javascript variables not working

I am trying to grab some text content (HTML comments) on the page and convert it into variables. The text content will be of the format:
I have constructed some Javascript that works up to a point, but will not go past the final variable declaration "var shorturl = ..."
Javascript code below:
$(document).ready(function() {
if (document.getElementById("ajax-gallery")) {
var shortcode = '<!-- [var module="gallery"; var id="1"; var type="single"; var data="only";] -->';
shortcode = shortcode.replace("<!-- [", "");
shortcode = shortcode.replace("] -->", "");
eval('shortcode');
var shorturl = "shorturl = " + module + "/shortcode_" + type + ".php?id=" + id + "&data=" + data;
eval('shorturl')
updateGallery(shorturl, "ajax-gallery");
}
});
I would have thought this would work, but apparently not. I know that eval is frowned upon but at present I cannot find a "nicer" method.

Run javascript code inside new window in Internet Explorer

I am trying to run some injected javascript code in a blank new popup
var popup = window.open('', 'name', options);
var scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.text = scriptSource;
popup.document.body.appendChild(scriptElement);
The javascript code works in FF and Chrome but I receive a HierarchyRequestError in IE (11). I've found an alternative way to write the last line with this one popup.document.head.innerHTML = scriptElement.outerHTML; but in this case the javascript is not recognised in any browser.
In PhpDebugToolbar at https://github.com/DracoBlue/PhpDebugToolbar/blob/master/pub/PhpDebugToolbar.js#L913 I use the following snippet, to create or update a custom PopUp with custom content.
var detail = window.open('', "php_debug_toolbar_window_" + key, "width=800,height=400,status=yes,scrollbars=yes,resizable=yes");
detail.document.write( [
'<script type="text/javascript">',
'if (!document.body) {document.write("<html><head><title></title></head><' + 'body></' + 'body></html>"); }',
'document.getElementsByTagName("title")[0].innerHTML = ' + JSON.stringify(title) + ';',
'var content = document.getElementById("content");', 'if (content) {', ' document.body.removeChild(content);', '}',
'content = document.createElement("div");', 'content.id="content";', 'content.innerHTML = ' + JSON.stringify(html) + ';',
'document.body.appendChild(content);', '<' + '/script>'
].join("\n"));
The important parts:
use document.write to initialize html>head+html>body structure
use a #content (or any other id) div for your content
JSON.stringify your content and set it with .innerHTML-Property of your #content div in JS
This is working for me quite good so far, so I am sure you can add your script tag like this, too.

HTML in string with JavaScript code, JS not working

Here is my test javascript function
<script type="text/javascript">
function test() {
var sHTML = "<script type='text/javascript'> " +
"function showmsg() { " +
"alert('message'); " +
"} " +
"<\/script>" +
"<div>" +
"<a href='#' onclick='javascript:showmsg(); return false;'>click</a>" +
"</div>";
var divTemp = document.createElement("div");
divTemp.innerHTML = sHTML;
var d = document.getElementById("div1");
d.appendChild(divTemp);
}
</script>
When I run this function, the div along with a tag is added in the div1, but when I click on anchor tag, it says showmsg is not defined, which is indicating that browser is NOT parsing the script tag.
How to achieve this without any 3rd party library?
Update:
The possible usage is, I want to allow user to create HTML templates along with JavaScript code, then my JS library will use those HTML templates to render user defined markup, plus allowing user to implement his/her custom logics through JS.
You need to run eval on the script contents when using innerHTML. Try something like:
var scripts = divTemp.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++) {
eval(scripts[i].textContent);
}
Obviously, you need to do this in end, after injecting the innerHTML into the DOM.
Browsers do not run JavaScript code when a <script> tag is dynamically inserted like that.
Instead of that, you can just define the function directly!
function test() {
window.showmsg = function() {
alert("message");
};
var sHTML = "<div>" +
"<a href='#' onclick='javascript:showmsg(); return false;'>click</a>" +
"</div>";
var divTemp = document.createElement("div");
divTemp.innerHTML = sHTML;
var d = document.getElementById("div1");
d.appendChild(divTemp);
}
Libraries like jQuery have code to strip <script> blocks out of text that's being stuffed into some element's innerHTML, and then evaluate it with eval(), so that's one thing to do if the code is somehow "stuck" in a block of content.
Using jquery, is this can help you :
$('<script>function test(){alert("message");};</' + 'script><div>click</div>').appendTo(document.body)
http://jsfiddle.net/TSWsF/

Passing javascript variable to jquery

Im facing some problems what i cannot solve for days now.
I wish to get the Position of an element which is have a uniqe ID
Code:
function e_div_show(sid,ctd)
{
var b_fos="t"+sid;
var pos = $(b_fos).offset();
alert(pos.top + ' ' + pos.left);
}
HTML Code:
<?php
...
echo ('<td ID="t'.$array['S_ID'].'">...</td>
...
?>
this is not working..
if i replace the ID to "b_fos" and i comment out the //var b_fos="t"+sid; it working fine.. however in this case the TD ID wont be unique becouse of the php array which generating the code.
Any help please how to define the pos correclty with a javascript variable?
Try changing:
var b_fos = "t" + sid;
To
var b_fos = "#t" + sid;
Try this code you have miss '#' before
function e_div_show(sid,ctd)
{
var b_fos="#t"+sid;
var pos = $(b_fos).offset();
alert(pos.top + ' ' + pos.left);
}

Categories