Getting a function to actually output HTML - javascript

Have some JavaScript running that's dynamically building an array of images.
Here's the simplified version:
var imgArray = new Array(
"mainBG.jpg",
"mainBG2.jpg",
"mainBG3.jpg",
"mainBG4.jpg"
);
var img = Math.floor(Math.random()*imgArray.length);
jQuery(document).ready(function() {
$("body").ezBgResize({img : "/lib/img/bkgr/" + imgArray[img]});
});
function generateThumbs(){
var t = document.getElementById("thumbs");
var ret = '';
for(i=0;i<imgArray.length;i++){
var image = imgArray[i];
ret += '<a href="#" onclick="changeBig(\''+image+'\')" /><img src="/lib/img/bkgr/'+image+'" alt="thumbnail image" width="77" height="44" /></a>';
}
return ret;
};
function changeBig(bg){
$("body").ezBgResize({img : "/lib/img/bkgr/" + bg});
}
Then in the page, it's being written out simply with:
<div class="scrollable">
<div class="items" id="thumbs">
<script>document.write(generateThumbs());</script>
</div>
</div>
Problem is, when I view the source, it never outputs actual HTML. The source just shows that line. Is there a way to get that function to actually output HTML into the page-- partially for SEO, but also so some jQuery can interact with it
?

When you view source all you see is the code returned to the browser from the webserver without any modifcations javascript has done to the dom. To have the code in the raw source you need to generate it on the server side.
To see the generated source with the javascript modifications you can use firebug in firefox or the built in developer tools in Chrome/Safari/IE9.

This will do the trick
$(function(){
$("#thumbs").html(generateThumbs());
});

Don't call document.write in the context of an HTML page. You should be doing something like this:
<script type="text/javascript" language="javascript">
document.getElementById('thumbs').innerHTML = generateThumbs();
</script>

Try:
$('#thumbs').html(generateThumbs());

Related

Loading an img object with a src in javascript

I want to add a thumbnail picture to a book's details, derived from the google books api, on the webpage. The code below will place the source code (api) for the appropriate book, first into the text field bookCover and then into the var copyPic, and then it should be copied into imgDisp, but it doesn’t. I can see that bookCover holds the right text, and have checked that copyPic holds the correct content.
<img id="imgDisp" src="http://books.google.com/books/content?
id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api" width="85" height="110"" />
$.getJSON(googleAPI, function(response) {
$("#title").html(response.items[0].volumeInfo.title);
$("#subtitle").html(response.items[0].volumeInfo.subtitle);
$("#author").html(response.items[0].volumeInfo.authors[0]);
$("#description").html(response.items[0].volumeInfo.description);
$("#version").html(response.items[0].volumeInfo.contentVersion);
$("#modeR").html(response.items[0].volumeInfo.readingModes.text);
$("#bookCover").html(response.items[0].volumeInfo.imageLinks.thumbnail);
var copyPic = document.getElementById('bookCover').innerHTML;
document.getElementById("imgDisp").src=copyPic;
Does anyone know why not? Or can I put the api details directly into imgDisp (can’t find such code syntax anywhere on the net)? Everything else is working fine. If I put a src in directly, then it works e.g.
document.getElementById("imgDisp").src = “http://.....api”
but not with a variable.
Without more info - eg, I can't see where the getJSON() function ends or what the URL's are, I can't see what the issue may be (except, perhaps, as in my last comment).
I idea seems ok, as I can replicate it (in a cut-down version of course):
function copyImageSource() {
let d = document.getElementById("bookCover").innerHTML;
document.getElementById("imgDisp").src = d;
}
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover">https://duckduckgo.com/assets/icons/meta/DDG-icon_256x256.png</div>
<img id="imgDisp" src="">
I assume that this is the sort of thing you are trying to achieve?
(javascript -> jquery:
let copyPic = $("#bookCover").html();
$("#imgDisp").attr("src", copyPic);
)
Version using jquery:
function copyImageSource() {
let d = $("#bookCover");
d.html("http://books.google.com/books/content?id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api");
let dCopy = d.html().replace(/&/g, "&");
$("#imgDisp").attr("src", dCopy);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover"></div>
<img id="imgDisp" src="https://www.picsearch.com/images/logo.png"/>
If you have jQuery you can easily do the following:
let source = 'https://img.com/image.png';
//to get the image object that has the above just do this:
let img = $('img[src="' + source + '"]');

Remove some auto generated text from a heading with javascript

I'm using uncode theme and I have a page heading that is showing 'Archive: Portfolio'
I want to remove the 'Archive:' bit from that heading.
In the source it looks like this:
<h1 class="header-title h1"><span>Archives: Projects</span></h1>
I have tried removing Archive from all the page titles with Yoast SEO plugin but it is still showing.
Is there a way to remove that word with javascript maybe does anyone know?
Thanks!
I'd be wary in removing it via javascript. It seems to me that adding a piece of text somewhere in the code's execution, and then removing it on the client-side smells like "contrived complexity".
Take a look at the wordpress template hierarchy, and manually search for the template file that's rendering the Archives: string of text.
I'd start with archive.php, and then fall my way up through other archive-*.php pages, then to taxonomy.php category.php, and so on.
If you're comfy in the command line, you might also consider grepping for the string: grep -r /path/to/wp/theme "Archive:" and sifting through the results to find the template file(s) with that on one of their lines.
But if you insist on removing the string via javascript, you might try dropping something like this at the bottom of the <body>, via a function in functions.php:
function remove_archive_text_via_js() {
if (is_archive()) { ?>
<script type="text/javascript">
var archiveHeaders = document.getElementsByClassName('header-title');
for (i = 0, headerCount = archiveHeaders.length; i < headerCount; i++) {
var replacedText = archiveHeaders[i].textContent.replace('Archives: ', '');
archiveHeaders[i].textContent = replacedText;
}
</script>
<?php }
}
add_action('wp_footer', 'remove_archive_text_via_js');
var elem = document.getElementsByClassName('header-title h1');
var innerSpan = elem[0].getElementsByTagName('span');
innerSpan[0].innerHTML = innerSpan[0].innerHTML.replace('Archives: ', 'jsfiddle');
jsfiddle: https://jsfiddle.net/orcadj3u/
$(function() {
$( "h1 span" ).each(function( index ) {
var newtext = $(this).text().replace("Archives: ", " ");
$(this).html(newtext);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1 class="header-title h1"><span>Archives: Projects</span></h1><br>
<h1 class="header-title h1"><span>Archives: Solutions</span></h1><br>
<h1 class="header-title h1"><span>Archives: Yozgat</span></h1><br>
<h1 class="header-title h1"><span>Archives: Turkey</span></h1><br>

Why am i getting this missing } after property list error? :(

I know this is something easy but I just can't see it. Can anyone tell me why I am getting the error "missing } after property list" for the following code:
<script type="text/javascript">
$(".single_image").live("click", function() {
jwplayer().load({
file: 'utubeurl'
});
});​
</script>
the whole of the code is shown below:
$(xml).find('item').each(function(i){
var current=$(this);
var ttl=current.find('title:first').text();
var thum=current.find('thumbnail:first').text();
var cat=current.find('category:first').text().split(',');
var desc = current.find('description:first').text();
var utubeurl = current.find('youtubeurl:first').text();
var fbshareurl = current.find('facebookshareurl:first').text();
var twturl = current.find('twitterurl:first').text();
var nbcurl = current.find('nbcsiteurl:first').text();
var item = {
title:ttl,
thumbnail:thum,
category:cat,
description:desc,
youtubeurl:utubeurl,
facebookshareurl:fbshareurl,
twitterurl:twturl,
nbcsiteurl:nbcurl,
obj:$('<div class="'+options.itemClass+'"><a id="'+parentId+'" class="single_image" title="'+desc+'"><script type="text/javascript"> $(".single_image").live("click",function(){ jwplayer().load({file:'+utubeurl+'}); }); </script><img src="'+thum+'" /></a><div class="show_lightbox_title"><strong>'+ttl+'</strong></div><ul id="social"><li><iframe src="'+fbshareurl+'" class="iframe_style" scrolling="no" frameborder="0" allowtransparency="true"/></li><li><a class="twtbtn" href="'+twturl+'" target="_blank"><img src="images/twitter_btn.gif"></a></li><a class="nbcbtn" href="'+nbcurl+'" target="_blank"><img src="images/showPages_btn.gif"></a></div>')
};
shows.push(item);
});
You need to quote your property value, here:
obj:$('<div class="'+options.itemClass+'"><a id="'+parentId+'" class="single_image" title="'+desc+'"><script type="text/javascript"> $(".single_image").live("click",function(){ jwplayer().load({file:'+utubeurl+'}); }); </script><img src="'+thum+'" /></a><div class="show_lightbox_title"><strong>'+ttl+'</strong></div><ul id="social"><li><iframe src="'+fbshareurl+'" class="iframe_style" scrolling="no" frameborder="0" allowtransparency="true"/></li><li><a class="twtbtn" href="'+twturl+'" target="_blank"><img src="images/twitter_btn.gif"></a></li><a class="nbcbtn" href="'+nbcurl+'" target="_blank"><img src="images/showPages_btn.gif"></a></div>')
...this:
'... jwplayer().load({file:'+utubeurl+'}); ...'
...needs to be:
'... jwplayer().load({file:"'+utubeurl+'"}); ...'
...note the extra quotes. Not sure if adding those quotes will break your looooooooong (difficult to read/support) string, you might need to escape them. But you get the idea?
Cheers
Try putting the file property under quote marks , like so:
function () {
'file' : 'utubeurl'
}
--EDIT:
My bad , forget it , I was confusing with json, jquery and maybe some other j out there, you're definning a property , no need to make the name of the memory slot a string .
When I copy and paste that block of code, I see an extra character trailing the second closing });
Removing that executes fine in console for me, so if that is not the source of the error I would look elsewhere on the page.
Is the page publicly accessible?
Solved the problem by passing a variable through href and then passing it into the command to play the url.
var item = {
title:ttl,
thumbnail:thum,
category:cat,
description:desc,
youtubeurl:utubeurl,
facebookshareurl:fbshareurl,
twitterurl:twturl,
nbcsiteurl:nbcurl,
obj:$('<div class="'+options.itemClass+'"><img src="'+thum+'" /><div class="show_lightbox_title"><strong>'+ttl+'</strong></div><ul id="social"><li><iframe src="'+fbshareurl+'" class="iframe_style" scrolling="no" frameborder="0" allowtransparency="true"/></li><li><a class="twtbtn" href="'+twturl+'" target="_blank"><img src="images/twitter_btn.gif"></a></li><a class="nbcbtn" href="'+nbcurl+'" target="_blank"><img src="images/showPages_btn.gif"></a></div>')
};
shows.push(item);
});
setSetter();
}
});
}
utubeurlParser = function(url){
jwplayer().load({file: [url]});}

Javascript problem when returning function?

I have a function like this:
function ban_rot(){
var bnr = new Array();
bnr[0] = "/Graphics/adv/businesscrown.gif";
bnr[1] = "/Graphics/adv/webbdesigna.jpg";
num = bnr.length - 1;
i = Math.round(Math.random(bnr) * num);
return '<img src=\"' + i + '\" alt=\"\" border=\"1px\" style=\"border-color:#000;\">';
}
I then have a html code:
<td align="center"><a href="http://www.domain.com" class="links4">
<script type="text/javascript">return ban_rot();</script>
</a>
</td>
The above doesn't work, ie nothing shows up. empty.
Any ideas?
Thanks
return doesn't work like echo in PHP. If you want to output into your HTML, you need to create an element and then update it (for instance, by editing it's innerHTML attribute).
<td align="center"><a href="http://www.businesscrown.com" class="links4">
<div id="banner"></div>
<script type="text/javascript">
document.getElementById('banner').innerHTML = ban_rot();
</script>
</a>
</td>
Since the ban_rot() function returns a String and you want to display the String you may need to do this:
<script type="text/javascript">document.write( ban_rot());</script>
I think you're conflating the server-side templating paradigm with client-side JavaScript. Even if you return a string from a JavaScript function, as you have done, it doesn't magically insert that string into the DOM and remove the <script> tags.
Instead, you need to use DOM API methods to turn your function-returned string into an actual HTML element, like this: document.getElementById('some_element_id').innerHTML = ban_rot();
Just returning the HTML string won't print it.
You need to do something like document.write().
"return" is used to return a value from a function. You can not use it to put code in a page. You can use document.write(...) but I would highly recommend you learn jQuery. It makes modifying the html much easier.
you can't just return in the middle of a document.
<td align="center">
<a href="http://www.domain.com" class="links4" id='myLink'></a>
<script type="text/javascript">
document.getElementById('myLink').innerHTML = ban_rot();
</script>
</td>
note that you have to give your link an id so that it may be referenced (or pick another wya to find it).
the preferred way to do all this is to construct new elements with the DOM methods.
function ban_rot() {
var bnr = new Array();
bnr[0] = "/Graphics/adv/businesscrown.gif";
bnr[1] = "/Graphics/adv/webbdesigna.jpg";
num = bnr.length - 1;
i = Math.round(Math.random(bnr) * num);
var img = document.createElement('img');
img.src = i.toString();
img.style.border = '1px solid #000';
var myLink = document.getElementById('myLink');
myLink.appendChild(img);
}
then you don't need to return anything- the method will add the image to the link.
<td align="center">
<a href="http://www.domain.com" class="links4" id='myLink'></a>
<script type="text/javascript">ban_rot();</script>
</td>

Changing data content on an Object Tag in HTML

I have an HTML page which contains an Object tag to host an embedded HTML page.
<object style="border: none;" standby="loading" id="contentarea"
width="100%" height="53%" type="text/html" data="test1.html"></object>
However, I need to be to change the HTML page within the object tag. The current code seems to create a clone of the object and replaces the existing object with it, like so:
function changeObjectUrl(newUrl)
{
var oContentArea = document.getElementById("contentarea");
var oClone = oContentArea.cloneNode(true);
oClone.data = newUrl;
var oPlaceHolder = document.getElementById("contentholder");
oPlaceHolder.removeChild(oContentArea);
oPlaceHolder.appendChild(oClone);
}
This seems a rather poor way of doing this. Does anyone know the 'correct' way of changing the embedded page?
Thanks!
EDIT: In response to answers below, here is the full source for the page I am now using. Using the setAttribute does not seem to change the content of the Object tag.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test</title>
<script language="JavaScript">
function doPage()
{
var objTag = document.getElementById("contentarea");
if (objTag != null)
{
objTag.setAttribute('data', 'Test2.html');
alert('Page should have been changed');
}
}
</script>
</head>
<body>
<form name="Form1" method="POST">
<p><input type="button" value="Click to change page" onclick="doPage();" /></p>
<object style="visibility: visible; border: none;" standby="loading data" id="contentarea" title="loading" width="100%" height="53%" type="text/html" data="test1.html"></object>
</form>
</body>
</html>
The Test1.html and Test2.html pages are just simple HTML pages displaying the text 'Test1' and 'Test2' respectively.
You can do it with setAttribute
document.getElementById("contentarea").setAttribute('data', 'newPage.html');
EDIT:
It is also recommended that you use the window.onload to ensure that the DOM has loaded, otherwise you will not be able to access objects within it.
It could be something like this:
function changeData(newURL) {
if(!document.getElementById("contentarea"))
return false;
document.getElementById("contentarea").setAttribute('data', newURL);
}
window.onload = changeData;
You can read more about window.onload here
This seems to be a browser bug, setAttribute() should work. I found this workaround, which seems to work in all browsers:
var newUrl = 'http://example.com';
var objectEl = document.getElementById('contentarea');
objectEl.outerHTML = objectEl.outerHTML.replace(/data="(.+?)"/, 'data="' + newUrl + '"');
The above solutions did not work properly in Firefox, the Object tag doesn't refresh for some reason. My object tags show SVG images.
My working solution for this was to replace the complete Object node with a clone:
var object = document.getElementById(objectID);
object.setAttribute('data', newData);
var clone = object.cloneNode(true);
var parent = object.parentNode;
parent.removeChild(object );
parent.appendChild(clone );
Here's how I finally achieved it. You can do
document.getElementById("contentarea").object.location.href = url;
or maybe
document.getElementById("contentarea").object.parentWindow.navigate(url);
The Object element also has a 'readyState' property which can be used to check whether the contained page is 'loading' or 'complete'.
I found a very simple solution that also works in Chrome. The trick is to make the object (or a parent element) invisible, change the data attribute, and then make the object visible again.
In the code below, it is assumed that object_element is the object element and parent_element is the parent, and url is the url of the data.
parent_element.style.display = 'none'; // workaround for Chrome
object_element.setAttribute('data', url);
parent_element.style.display = '';
Following user2802253, I use this one on Safari and Firefox, which also forces a redraw. (sorry, not enough reputation to post as a simple comment).
theObject.style.visibility = null;
theObject.setAttribute("data", url);
theObject.style.visibility = "visible";
var obj = document.getElementById("pdfDoc");
obj.setAttribute('data', newPdf);
worked on Chrome version 54 and Safari, but didn't work on IE 11
what worked on them all
var obj = document.getElementById("pdfDoc");
obj.setAttribute('data', newPdf);
var cl = obj.cloneNode(true);
var parent = obj.parentNode;
parent.removeChild(obj);
parent.appendChild(cl);
This snippet did the job in my case
var object = document.getElementById(objectID);
object.setAttribute('data', newData);
var clone = object.cloneNode(true);
var parent = object.parentNode;
parent.removeChild(object );
parent.appendChild(clone );
<div id='myob'>
<object style="border: none;" standby="loading" id="contentarea"
width="100%" height="53%" type="text/html" data="test1.html"></object>
</div>
$('#myob').html($('#myob').html());
Changing the data attribute should be easy. However, it may not work perfectly on all browsers.
If the content is always HTML why not use an iframe?
Antoher way of doing it, you could embed the object in a DIV
var newUrl = 'http://example.com';
var divEl = document.getElementById('divID');
var objEl = document.getElementById('objID');
objEl.data = newUrl;
// Refresh the content
divEl.innerHTML = divEl.innerHTML;
I think this is a better way to achieve your objective.
Html:
<div id="mytemplate"><div>
Js:
function changeTemplate(t){
var mytemplate = document.getElementById("mytemplate");
mytemplate.innerHTML = '<object type="text/html" data=' + t + '></object>';
}
changeTemplate('template.html');
changeTemplate('whatever.html');
var content_area = document.getElementById("contentarea");
content_area.data = newUrl;
Refreshes object in Chrome Version 42.0.2311.90 m
the main reason of this issue is using "/" in local files.
The Wrong Code :
var obj = document.getElementById("hostedhtml");
obj.setAttribute('data', "pages\page2.html");
The Right Code :
var obj = document.getElementById("hostedhtml");
obj.setAttribute('data', "pages\\page2.html");

Categories