IE8 display overlap occurs using insertBefore - javascript

I'm attempting to move div elements from one section to another using node.insertBefore and order the insertion alphabetically. Upon clicking (in this case clicking A) to reorder I have a problem with elements overlapping as seen in the image below:
The code I'm using to produce this follows; I'm sorry it's a little long, but if you copy it into an html file in it's entirety you'll easily see my problem.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var moveUp, moveDown;
var moveUp = function() {
var e = window.event.srcElement;
var firstBlock = document.getElementById('firstBlock');
var moved = false;
for (var i=0; i<firstBlock.childNodes.length; i++) {
if (firstBlock.childNodes[i].innerText > e.innerText) {
firstBlock.insertBefore(e, firstBlock.childNodes[i]);
moved = true;
break;
}
if (!moved) firstBlock.appendChild(e);
}
e.onclick = moveDown;
};
var moveDown = function() {
var e = window.event.srcElement;
var secondBlock = document.getElementById('secondBlock');
var moved = false;
for (var i=0; i<secondBlock.childNodes.length; i++) {
if (secondBlock.childNodes[i].innerText > e.innerText) {
secondBlock.insertBefore(e, secondBlock.childNodes[i]);
moved = true;
break;
}
if (!moved) secondBlock.appendChild(e);
}
e.onclick = moveUp;
};
</script>
<title>Test</title>
</head>
<body>
<div id="firstBlock" style="background-color:#dddddd;">
<div onclick="moveDown()">A</div>
<div onclick="moveDown()">B</div>
<div onclick="moveDown()">C</div>
<div onclick="moveDown()">D</div>
</div>
<div id="secondBlock">
<div onclick="moveUp()">E</div>
<div onclick="moveUp()">F</div>
<div onclick="moveUp()">G</div>
<div onclick="moveUp()">H</div>
</div>
</body>
</html>
Am I doing something wrong/odd? Can this be fixed/worked around? Thanks in advance for your help!
Edit:
I can't currently test in any other browsers.
I notice that once one section fills up, the highlighting no longer readjusts itself when items move between sections.
Edit 2: Result of jsfiddle posted by Jared

Happened to come back to this question now. In case anyone else is having this problem, I ended up having to replace the div list with a table and rearrange table rows. Another option may be to use a list.

Related

Auto Click all Links In Div ID

I have a WP blog page which shows recent posts using category shortcodes
On that page, i have a list of links leading to their posts.
I can't edit the links to add id or class to them, so i am manually using a div to wrap the shortcode and a javascript which makes the links open to new tab upon click, is there a way i can open all the links to new tabs open single click? (REMEMBER, I CANT EDIT THE LINKS)
Here is my codes
<!--- i cant edit the links below ----->
<div id="boss" class="boss">
Example 1
Example 2
Example 3
Example 4
</div>
JAVASCRIPT
<script type="text/javascript">
window.onload = function(){
var a = document.getElementById('boss').getElementsByTagName('a');
for (var i=0; i<a.length; i++){
a[i].setAttribute('target', '_blank');
}
}
</script>
am trying to load all the links to their new tabs upon click
<div onclick="boss();">Something To Click On</div>
ITS NOT WORKING, ANY HELP PLS?
Fullcode example:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function boss() {
var a = document.getElementById('boss').getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
a[i].setAttribute('target', '_blank');
openNewTab(a[i], "click");
}
}
function openNewTab(obj, evtName) {
try {
if (obj.dispatchEvent !== null && obj.dispatchEvent !== undefined) {
//var event = new Event(evtName);
var event = document.createEvent("MouseEvents");
event.initMouseEvent(evtName, true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
obj.dispatchEvent(event);
} else if (obj.fireEvent !== null && obj.fireEvent !== undefined) {
event = document.createEventObject();
event.button = 1;
obj.fireEvent("on" + evtName, event);
obj.fireEvent(evtName);
} else {
obj[evtName]();
}
} catch (e) {
alert(e);
}
}
</script>
</head>
<body>
<div onclick="boss();">Something To Click On</div>
<div id="boss">
Example 1
Example 2
Example 3
Example 4
</div>
</body>
</html>
That would be easy with jQuery. You can use .each() and .attr() to achieve it.
NOTE
Try this script in your WordPress. Since the below output is a iframe, it won't work!
$ = jQuery;
$(document).ready(function(){
$("#boss > a").each(function(){
$(this).attr("target","_blank");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="boss" class="boss">
Example 1
Example 2
Example 3
Example 4
</div>
Good Luck :)

.innerHTML: Cannot set property 'innerHTML' of null

First, I am completely new to coding and have been using self-teaching tools to learn Javascript in my free time. I've learned enough to start building my own projects. My first attempt is to build a randomizer (in this case, random restaurant names). The Javascript works through my tests in the console as do the buttons. However, I cannot seem to get the .innerHTML to work and I'm not sure what I'm missing. I've done several searches here and none of the solutions I've found seem to be working.
The error I'm getting is listed in the title and it is appearing at line 29.
Here is Javascript:
var randomRestaurant = {
restaurantName: [],
findRestaurant: function() {
var restaurantName = Math.random();
if (restaurantName < 0.20) {
this.restaurantName.push("China Taste");
}
else if (restaurantName < 0.40) {
this.restaurantName.push("Pizza Johns");
}
else if (restaurantName < 0.60) {
this.restaurantName.push("Liberatore's");
}
else if (restaurantName < 0.80) {
this.restaurantName.push("Bill Bateman's");
}
else {
this.restaurantName.push("R&R Taqueria");
}
},
clearRestaurant: function() {
randomRestaurant.restaurantName.splice(0, 1);
}
};
var randomRestaurantButton = document.getElementById('randomRestaurantName');
randomRestaurantButton.addEventListener('click', function() {
randomRestaurant.findRestaurant();
document.getElementById("restaurantNameDisplay").innerHTML = randomRestaurant.restaurantName[0]; //<--line 29
});
var randomRestaurantButton = document.getElementById('refreshRestaurant');
randomRestaurantButton.addEventListener('click', function() {
randomRestaurant.clearRestaurant();
randomRestaurant.findRestaurant();
document.getElementById("restaurantNameDisplay").innerHTML = randomRestaurant.restaurantName[0];
});
And here is my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div><h1>Random Restaurant!</h1>
<button id="randomRestaurantName">Click me for a random restaurant!</button>
</div>
<br>
<h2="restaurantNameDisplay"></h2="restaurantNameDisplay">
<div>
<br>
<button id="refreshRestaurant">Nah. Give me another one.</button>
</div>
</body>
<script src="script.js"></script>
</html>
Thanks for your help and hopefully it's not due to something stupid like a typo.
There are some problems here.
the h2 tag id should be
<h2 id="restaurantNameDisplay"></h2>
your buttons are set on the same variable name, change the second to
var refreshRestaurantButton = document.getElementById('refreshRestaurant');
refreshRestaurantButton.addEventListener('click', function () {
randomRestaurant.clearRestaurant();
randomRestaurant.findRestaurant();
document.getElementById("restaurantNameDisplay").innerHTML = randomRestaurant.restaurantName[0];
});
If it's still not working, you should call your script after the page load event.
so insert your javascript code to a function (e.g. "myFunc()") and change your html body tag to:
body onload="myFunc()">
Most probably this line <h2="restaurantNameDisplay"></h2="restaurantNameDisplay"> should be
<h2 id="restaurantNameDisplay"></h2>

jsPDF addHTML get full contents of scrolling element

How do I get jsPDF to create an image/pdf from an element that has overflow set so that it has scrollbars. The following example pasted into the addHTML Have a Play page (http://mrrio.github.io/jsPDF/) will only generate a pdf for the section of the div that is showing, even if I choose the "middle" div:
var outer = document.createElement('div');
outer.style.height = "100px";
outer.style.overflow = "scroll";
var middle = document.createElement('div');
for ( var i=0; i<35;i++ ) {
var inner = document.createElement('div');
inner.style.border = "thick solid #0000ff";
inner.style.padding = "10px";
middle.appendChild(inner);
}
outer.appendChild(middle);
document.body.appendChild(outer);
var pdf = new jsPDF('p','pt','a4');
pdf.addHTML(outer,function() {
var string = pdf.output('datauristring');
$('.preview-pane').attr('src', string);
});
(Basically, this is creating a div with a scrollbar, adding a div inside, then adding a whole bunch of divs inside the middle one. There are enough to scroll off screen, so the pdf doesn't pick them up. I thought of popping out a new window, but if I do that, I have to figure out all the different style sheets to pull into the popout.)
Take a look at this discussion: https://github.com/MrRio/jsPDF/issues/270:
I am using addHtml() method with html2canvas.js for making pdf , but for large data table it is not generating pdf ,for short content going fine. Please help me here is my code
To which Flamenco replies:
I started working on a feature to breakup long HTML pages.
Try This:
https://rawgit.com/Flamenco/jsPDF/text-html-table-page-break/examples/html2pdf/test-long-html-table.html
The example code creates a long table and generates a PDF with this. Perhaps his setup is of use to you.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Long Table</title>
</head>
<script src='../../libs/require/require.js'></script>
<script>
require_baseUrl_override = '../../';
require(['../../libs/require/config'], function(){
require(['jspdf.plugin.canvas', 'libs/html2pdf', 'libs/html2canvas/dist/html2canvas', 'libs/saveas'], function(){
var pdf = new jsPDF('p', 'pt', 'a3');
// Enable auto page wrap (there are still margin-top issues...)
pdf.context2d.pageWrapY = pdf.internal.pageSize.height-20;
// create a long table
var table = document.createElement('table');
for (var i=1; i<1000; i++){
var tr=document.createElement('tr');
var td=document.createElement('td');
td.innerHTML = "Item " + i;
tr.appendChild(td);
table.appendChild(tr);
}
document.body.appendChild(table);
// render body to pdf
html2pdf(document.body, pdf, function(){
pdf.save('Test.pdf');
});
}); // require
}); // require
</script>
<body>
</body>
</html>
The code is a bit mangled, but it works.

How to make a text slider that moves next or previous in javascript?

Ok so I've revised the markup/code to make it easier to understand. Using JavaScript I want to know how to create a text slider that changes a paragraph in html5 either "forwards" or "backwards" on click?
I only want one div to show at a time and the first div (div_1) needs to be visible at the beginning as a default setting. I also want to be able to add more text divs to it in the future. I'm new to JavaScript so I want to keep it as simple as possible.
I've had a go creating it in JavaScript which hasn't worked, I'm not sure if I'm going about this the right way.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
.showHide {
display: none;
}
</style>
<script type="text/javascript">
var sdivs = [document.getElementById("div_1"),
document.getElementById("div_2"),
document.getElementById("div_3"),
document.getElementById("div_4")];
function openDiv(x) {
//I need to keep div_1 open as a starting point
sdivs[0].style.display ="block";
var j;
for (var j = 0; j < sdivs.length; j++) {
if (j === x) {
continue;
}
else {
sdivs[j].style.display = "none";
}
}
}
</script>
<title>text</title>
</head>
<body>
forward
backwards
<div id="text_holder">
<div id="div_1" class="showHide">One</div>
<div id="div_2" class="showHide">Two</div>
<div id="div_3" class="showHide">Three</div>
<div id="div_4" class="showHide">Four</div>
</div>
</body>
</html>
When dealing with multiple elements like this, I've found CSS alone to be insufficient (though its brilliant for modifying simple hover states or whatever). This one method here is pretty simple and specific to this one set of markup (so modify as you see fit). More importantly - its to illustrate how to set up a simple javascript "class" to handle your logic.
http://jsfiddle.net/1z13qb58/
// use a module format to keep the DOM tidy
(function($){
// define vars
var _container;
var _blurbs;
var _blurbWidth;
var _index;
var _clicks;
// initialize app
function init(){
console.log('init');
// initialize vars
_container = $('#text_holder .inner');
_blurbs = $('.blurb');
_blurbWidth = $(_blurbs[0]).innerWidth();
_clicks = $('.clicks');
_index = 0;
// assign handlers and start
styles();
addEventHandlers();
}
// initialize styles
function styles(){
_container.width(_blurbs.length * _blurbWidth);
}
// catch user interaction
function addEventHandlers(){
_clicks.on({
'click': function(el, args){
captureClicks( $(this).attr('id') );
}
});
}
// iterate _index based on click term
function captureClicks(term){
switch(term){
case 'forwards':
_index++;
if(_index > _blurbs.length - 1){
_index = 0;
}
break;
case 'backwards':
_index--;
if(_index < 0){
_index = _blurbs.length - 1;
}
break;
}
updateView();
}
// update the _container elements left value
function updateView(){
//_container.animate({
//'left' : (_index * _blurbWidth) * -1
//}, 500);
_container.css('left', ((_index * _blurbWidth) * -1) + 'px');
}
init();
})(jQuery);
I'm using jQuery to handle event binding and animation, but, again - there are lots of options (including a combination of vanilla javascript and CSS3 transitions).
I'll note also that this is all html4 and css2 (save your doctype).
Hopefully that helps -

wanted: simple HTML file that does disclosure triangle <div> hide/reveal

I have a program that produces a text report. I want it to make an HTML report with multiple disclosure triangles, so that when you click a triangle more of the report shows or hides. I am okay with embedding JavaScript inside the file, but I really want it all in a single file, with no additional files. Is there an easy way to do this with modern browsers?
If you don't care about compatibility with Internet Explorer, you could use the html tag: http://www.w3schools.com/tags/tag_details.asp
Its a very quick way to prototype disclosure triangles.
For example:
<details>
<summary>The contents of the summary tag is always visible</summary>
<p>Everything else inside the details tag will be hidden in a disclosure triangle</p>
</details>
The simplest way is something like this:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<style>.wrapper div { display:none;}</style>
<script>
$(function() {
$('.wrapper h2').click(function() { $(this).next().toggle();});
});
</script>
</head>
<body>
<div class="wrapper">
<h2>Example header 1</h2>
<div>bodytext 1</div>
</div>
<div class="wrapper">
<h2>Example header 2</h2>
<div>bodytext 2</div>
</div>
<div class="wrapper">
<h2>Example header 3</h2>
<div>bodytext 3</div>
</div>
</body>
</html>
I have made a simple working example here: http://jsfiddle.net/NXuQt/1/
It isn't pretty but should give you the simple template you need.
Note that in this solution, the entire header is click-able... I figure adding an image and changing it as part of the click event is something you can take care of yoruself, otherwise let me know :)
Note: The javascript is based on the inclusion of the jQuery library.
EDIT: I updated the answer to copy/paste ready working code, the reason you couldn't make it work as it was, was because i had only taken the essentials from the fiddle example. The fiddle automatically ran the click handler initialization at DOMready, which the updated example now has built in :)
With straight HTML, no. That's not what it's for. You will need to use a scripting language, either JavaScript or VBScript, most likely.
This is a script I've used in the past (not mine, but I don't have the URI of the original):
var timerlen = 5;
var slideAniLen = 250;
var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();
function slidedown(objname)
{
if(moving[objname])
return;
if(document.getElementById(objname).style.display != "none")
return; // cannot slide down something that is already visible
moving[objname] = true;
dir[objname] = "down";
startslide(objname);
}
function slideup(objname)
{
if(moving[objname])
return;
if(document.getElementById(objname).style.display == "none")
return; // cannot slide up something that is already hidden
moving[objname] = true;
dir[objname] = "up";
startslide(objname);
}
function startslide(objname)
{
obj[objname] = document.getElementById(objname);
endHeight[objname] = parseInt(obj[objname].style.height);
startTime[objname] = (new Date()).getTime();
if(dir[objname] == "down")
{
obj[objname].style.height = "1px";
}
obj[objname].style.display = "block";
timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
}
function slidetick(objname)
{
var elapsed = (new Date()).getTime() - startTime[objname];
if (elapsed > slideAniLen)
{
endSlide(objname)
}
else
{
var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
if(dir[objname] == "up")
d = endHeight[objname] - d;
obj[objname].style.height = d + "px";
}
return;
}
function endSlide(objname)
{
clearInterval(timerID[objname]);
if(dir[objname] == "up")
obj[objname].style.display = "none";
obj[objname].style.height = endHeight[objname] + "px";
delete(moving[objname]);
delete(timerID[objname]);
delete(startTime[objname]);
delete(endHeight[objname]);
delete(obj[objname]);
delete(dir[objname]);
return;
}
function toggleSlide(objname)
{
if(document.getElementById(objname).style.display == "none")
{
// div is hidden, so let's slide down
slidedown(objname);
}
else
{
// div is not hidden, so slide up
slideup(objname);
}
}
You would assign a call to toggleSlide() to the onclick() event of the element you want to toggle.
CSS:
.hidden {
display: none;
}
Javascript:
function createSection(section, hidden) {
var triangle = section.children[0]; // assumes the triangle image is the first child of a section (see HTML)
var contents = section.children[1];
triangle.onclick = function() {
if (contents.className.indexOf("hidden") != -1) { // the section is hidden
contents.className = contents.className.replace("hidden", "");
} else { // the section wasn't hidden
contents.className += " hidden";
}
}
if (hidden) {
contents.className += " hidden";
}
}
// Create the sections when window loads
window.onload = function() {
createSection(document.getElementById("section1"));
createSection(document.getElementById("section2"), true);
}
HTML:
<div id="section1">
<img src="triangle.jpg"></img>
<div>This is the section content</div>
</div>
<div id="section2">
<img src="triangle.jpg"></img>
<div>this section is hidden by default</div>
</div>
Obviously you would have to change some things to your own html file
Well, after some fiddling around, I was able to make a file that does what I want using the switchcontent.js and switchicon.js javascript files I found at http://www.dynamicdrive.com/dynamicindex17/switchcontent2.htm
Here's my code, based on editing down theirs:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Drive DHTML scripts- Switch Content Script II (icon based)</title>
<script type="text/javascript" src="switchcontent.js" ></script>
<script type="text/javascript" src="switchicon.js"></script>
<style type="text/css">
/* Specifies title style */
.iconspan{
margin: 3px;
cursor:hand;
cursor:pointer;
font-weight: bold;
}
</style>
</head>
<body>
<span id="faqtable1-title" class="iconspan"></span>
How hot is our Sun?<br/>
<div id="faqtable1" class="icongroup2">
The surface of the Sun is around 5800 Kelvin, while the core reaches over 15 million Kelvin.
</div>
<br>
<span id="faqtable2-title" class="iconspan"></span>
How big is our Sun in terms of mass? <br/>
<div id="faqtable2" class="icongroup2">
The contains more than 99.8% of the total mass of our Solar System.
</div>
<script type="text/javascript">
var faqtable=new switchicon("icongroup2", "div")
faqtable.setHeader('▼', '▶') //Set header HTML
faqtable.collapsePrevious(false) //Allow more than 1 content to be open simultanously
faqtable.setPersist(true, 7) //Enable persistence to remember last switch content states for 7 days
faqtable.init()
</script>
</body>
</html>
It looks like this when closed:
▶ How hot is our Sun?
▶ How big is our Sun in terms of mass?
And this when opened:
▼ How hot is our Sun?
The surface of the Sun is around 5800 Kelvin, while the core reaches over 15 million Kelvin.
▼ How big is our Sun in terms of mass?
The contains more than 99.8% of the total mass of our Solar System.

Categories