Javascript Document.write not working - javascript

I am trying to dynamically populate a div based on the Innertext. Can anyone tell me why this is not working?
<div id="bs3" class="survey_dashboard_item" onclick="window.open('/building-specifications?bldgaddress=333 Johnson','_self');" style="font-size:40px; border:1px solid #bbb;">
<script>
window.onload = function Element(id) {
if (this.innerText == '333 Johnson') {
document.write('<div style="float:left; padding-left:10px; padding-top:10px;"><img src="/checkmark.png" title="Project Entered"></div>');
} else {
}
}
</script>
***333 Johnson***</div>

You don't need and you shouldn't use document.write() in such case.
You can do it with:
<script type="text/javascript">
function update_bs_3(){
var el = document.getElementById('bs3');
if (el.innerHTML.trim() == '333 Johnson') {
el.innerHTML = '<div style="float:left; padding-left:10px; padding-top:10px;"><img src="/checkmark.png" title="Project Entered"></div>';
}
}
</script>
Then put the event handler to your body element:
<body onload="update_bs3();">
And here is the fiddle http://jsfiddle.net/DxjGv/1/
EDIT: And here is the version for multiple divs:
HTML:
<div id="bs1" class="survey_dashboard_item" onclick="window.open('/building-specifications?bldgaddress=111 Steve','_self');" style="font-size:40px; border:1px solid #bbb;">
111 Steve</div>
<div id="bs2" class="survey_dashboard_item" onclick="window.open('/building-specifications?bldgaddress=222 Frankie','_self');" style="font-size:40px; border:1px solid #bbb;">
222 Frankie</div>
<div id="bs3" class="survey_dashboard_item" onclick="window.open('/building-specifications?bldgaddress=333 Johnson','_self');" style="font-size:40px; border:1px solid #bbb;">
333 Johnson</div>
JS:
function update_bs_divs(){
var divs = {
'bs1': {
'match': '111 Steve',
'replacement': '<div>Steve replaced</div>'
},
'bs2': {
'match': '222 George',
'replacement': '<div>George replaced</div>'
},
'bs3': {
'match': '333 Johnson',
'replacement': '<div>Johnson replaced</div>'
}
};
for (var id in divs) update_div(id, divs[id].match, divs[id].replacement);
};
function update_div(id, match, replacement){
var el = document.getElementById(id);
if (!el || (el.innerHTML.trim() != match)) return;
else el.innerHTML = replacement;
}
window.onload = update_bs_divs;
Save this JS code in a file and include it in your HTML head section.
Fiddle is here - http://jsfiddle.net/DxjGv/2/

For three reasons:
You are running the code when the document is complete, then document.write will either replace the entire document (as document.open is implicitly called), or it is ignored, depending on the browser. You can't write to the document when it has been parsed already.
The context of the method (this) is not the element that the script tag is inside, it's the object where the event happens, in this case the window object.
The innerText property only works in Internet Explorer.
Put the script tag outside the div, otherwise it may interfer with your check. You can use the innerHTML property to get and set the content:
<div id="bs3" class="survey_dashboard_item" onclick="window.open('/building-specifications?bldgaddress=333 Johnson','_self');" style="font-size:40px; border:1px solid #bbb;">333 Johnson</div>
<script> type="text/javascript"
window.onload = function() {
var el = document.getElementById('bs3');
if (el.innerHTML == '333 Johnson') {
el.innerHTML = '<div style="float:left; padding-left:10px; padding-top:10px;"><img src="/checkmark.png" title="Project Entered"></div>' + el.innerHTML;
}
};
</script>

Document.write prints a string into a blank page.
You have to use append/prependChild or innerHTML.

Related

This javascript won't work when exported from codepen. The code must run all in one page [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
I got this code from codepen: https://codepen.io/jsartisan/pen/wKORYL#=
What happens is I put it all in one page but it won't run. I tried to understand what is wrong with it, but it is just like the example in codepen above.
This happened before in other codepen examples but I couldn't figure out the reason why it won't work.
<html>
<head>
<style>
#filter_users {
width:100%;
padding:10px;
}
#users-list {
margin:0;
padding:0;
}
#users-list li {
list-style:none;
padding:10px;
margin:5px 0;
border: 1px solid #e4e4e4;
}
</style>
<script>
var users = [
'Goku',
'Naruto',
'Ichigo',
'Flash',
'Batman',
'Sherlock Holmes',
'Khaleesi',
'Steve Fox'
];
ul = document.getElementById("users-list");
var render_lists = function(lists) {
var li = "";
for (index in lists) {
li += "<li>" + lists[index] + "</li>";
}
ul.innerHTML = li;
}
render_lists(users);
// lets filters it
input = document.getElementById('filter_users');
var filterUsers = function(event) {
keyword = input.value.toLowerCase();
filtered_users = users.filter(function(user) {
user = user.toLowerCase();
return user.indexOf(keyword) > -1;
});
render_lists(filtered_users);
}
input.addEventListener('keyup', filterUsers);
</script>
</head>
<body>
<input type="text" placeholder="Search Users" id="filter_users"/>
<ul id="users-list">
</ul>
</body>
</html>
I expect it to work as in codepen.
You have to place the javascript code to the end of the document body. At the time the page gets rendered it doesn't see the element with the id users-list visible yet. Therefore putting the script to the end of the document will help. For more advanced scenarios you might consider using a method which would wait until the document is loaded and first then append the event listener. See e.g. Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it
<html>
<head>
<style>
#filter_users{
width:100%;
padding:10px;
}
#users-list{
margin:0;
padding:0;
}
#users-list li{
list-style:none;
padding:10px;
margin:5px 0;
border: 1px solid #e4e4e4;
}
</style>
</head>
<body>
<input type="text" placeholder="Search Users" id="filter_users"/>
<ul id="users-list">
</ul>
<script>
var users = [
'Goku',
'Naruto',
'Ichigo',
'Flash',
'Batman',
'Sherlock Holmes',
'Khaleesi',
'Steve Fox'
];
ul = document.getElementById("users-list");
var render_lists = function(lists){
var li = "";
for(index in lists){
li += "<li>" + lists[index] + "</li>";
}
ul.innerHTML = li;
}
render_lists(users);
// lets filters it
input = document.getElementById('filter_users');
var filterUsers = function(event){
keyword = input.value.toLowerCase();
filtered_users = users.filter(function(user){
user = user.toLowerCase();
return user.indexOf(keyword) > -1;
});
render_lists(filtered_users);
}
input.addEventListener('keyup', filterUsers);
</script>
</body>
</html>

Determining by function the element ID responsible for the function call. No jquery

I've assigned the same function to 2 different div elements. I'd like the function to determine which div element called the function by it's id. No jquery.
Am just not sure how to compare values with in the I assume would be sufficient if statement.
<head>
<script>
var x = document.getElementById('one')
var y = document.getElementById('two')
function foo(){
if(????){
x.style.color='red'
}
else if(????){
y.style.color='red'
}
}
</script>
<style>
#one, #two{width:50px; height:50px; border: solid black 5px;}
</style>
</head>
<div id='one' onclick='foo()'>hello</div>
<div id='two' onclick='foo()'>world</div>
Basically have div 'one' || 'two' call function foo() and have one of the responsible ID's properties changed.
Pass the event object and get the element through currentTarget:
function foo(e){
const currEl = e.currentTarget;
if (currEl.id === 'one') {
currEl.style.background = 'red';
}
if (currEl.id === 'two') {
currEl.style.background = 'green';
}
}
<div id='one' onclick='foo(event)'>hello</div>
<div id='two' onclick='foo(event)'>world</div>
You can pass the id of the div to foo.
<div id='one' onclick='foo(this.id)'>hello</div>
<div id='two' onclick='foo(this.id)'>world</div>
Then you can use the given id in the function foo like this:
function foo(id) {
document.getElementById(id).style.color = 'red';
}
function foo(id) {
document.getElementById(id).style.color = 'red';
}
#one, #two{width:50px; height:50px; border: solid black 5px;}
<div id='one' onclick='foo(this.id)'>hello</div>
<div id='two' onclick='foo(this.id)'>world</div>
if i'm not mistaken inline js is disencouraged.
you could do like this:
change the html to this:
<div class="mycatchid" id='one' >hello</div>
<div class="mycatchid" id='two' >world</div>
and use this js:
[...document.querySelectorAll('.mycatchid')].forEach(elem =>{
elem.addEventListener('click', function(){
if(this.id == 'one') { console.log(this.id)}
else console.log(this.id);
})
});
some notes, done in es6, can check a live example: https://jsfiddle.net/jrzh9wxL/

JS add +10 then sort DIV

GOAL script returns 20,13,12,11
Hi I am trying to make these two operations into a single operation on Load.
when loaded the page returns 3,2,10,1
so I have added a button to trigger a +10 function.
which returns 13,12,20,11
Both these functions work independently, however i need the the entire thing to work together so that it returns 20,13,12,11 on load
I don't want any buttons>>>>
<script src="js/jquery-1.4.1.min.js"></script>
<!--CSS-->
<style type="text/css">
.box {
border: 1px solid #000;
padding: 2px;
margin: 2px;
}
</style>
<!--JAVASCRIPT-->
<!-- (A) ADDS +10 to div No-->
<script type='text/javascript'>
$(document).ready(function(){
$("#increase").click(function(event){
$("div.box").each(function(idx,elem){
$(this).text( parseInt($(this).text(),10) +10 );
});
return false;
});
});
</script>
<div id="containerSort">
<!-- (B) SORTS div -->
<script type='text/javascript'>
$(function(){
var $divs = $("div.box");
$( "#numBnt" ).one("load", function() {
console.log('loaded')
var numericallyOrderedDivs = $divs.sort(function (a, b) {
return $(a).find("h7").text() < $(b).find("h7").text();
});
$("#containerSort").html(numericallyOrderedDivs);
});
});
</script>
<!--HTML-->
<div class="box"><h7>1</h7></div>
<div class="box"><h7>2</h7></div>
<div class="box"><h7>3</h7></div>
<div class="box"><h7>10</h7></div>
<img src="http://myscot.com/ImagesMain/myscotLogoResp120.jpg" id="numBnt"/>
</div>
<button id="increase">+10</button>
window.addEventListener("load", function(){...}) how would I combine the 2 functions to the event listener?
There are 2 ways to solve your problem
Call button's click event on page load.
Create a function which will wrap everything and assign it as eventListener.
Note:
$(function(){}) is a short hand for $(document).ready() and its a bad practice to have multiple document.ready functions.
H7 is not a valid header tag as mentioned by #Niet the Dark Absol. Browser might consider it as a custom element and process similar to span tag. (This is just a guess).
Below code:
$("div.box").each(function(idx, elem) {
$(this).text(parseInt($(this).text(), 10) + 10);
});
this will make multiple DOM operation. Its bad practice to manipulate DOM in a loop.
Following is a sample code. Also I have updated your code a bit.
JSFiddle.
$(document).ready(function() {
$("#increase").trigger("click");
});
$("#increase").click(function() {
var valArr = getValues();
valArr = addNumber(valArr);
valArr = sortValues(valArr);
createAndRenderHTML(valArr, "#containerSort");
});
function getValues() {
var returnArray = [];
$("div.box").each(function(id, el) {
returnArray.push(parseInt($(el).text(), 10));
});
return returnArray;
}
function addNumber(arr) {
return arr.map(function(item) {
return parseInt(item, 10) + 10;
});
}
function sortValues(arr) {
return arr.sort(function(a, b) {
return a > b ? -1 : a < b ? 1 : 0
});
}
function createAndRenderHTML(arr, el) {
var _html = arr.map(function(item) {
return "<div class='box'> <h7>" + item + "</h7></div>"
}).join("");
$(el).html(_html);
}
.box {
border: 1px solid #000;
padding: 2px;
margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<div id="containerSort">
<!--HTML-->
<div class="box">
<h7>1</h7>
</div>
<div class="box">
<h7>2</h7>
</div>
<div class="box">
<h7>3</h7>
</div>
<div class="box">
<h7>10</h7>
</div>
<img src="http://myscot.com/ImagesMain/myscotLogoResp120.jpg" id="numBnt" />
</div>
<button id="increase">+10</button>

Want to fetch the id of the different div elements on the click of p element using javascript

I have a page with p tags and div element, the div element is set with display:none in the starting so, I just want to display the different divs as shown below inside the body tag on the click of the p tag but i got stuck in fetching the different id of the divs. Please do help me out from this situation.Below is my code. Thanks
<script>
function toggle(id)// here is the function which gets the different ids of the div
{ var element = document.getElementById(id);
for(i=1; i<3; i++)
{
if(element[i].style.display == "none")
{
element[i].style.display = "block";
}
else
{
element[i].style.display = "none"
}
}
}
</script>
<body>
<p onclick="toggle('div1')">Sentence1</p>
<p onclick="toggle('div2')">Sentence2</p>
<div id="div1" name="Name 1" style="display:none; width:400px; height:300px; border:1px solid black; background-color:yellow;" id="div1">Barun Ghatak</div>
<div id="div2" style="display:none; width:400px; height:300px; border:1px solid black; background-color:black;" id="div2">Bhoopi</div>
</body>
You only have one of each div, so you don't need the loop. Just use
function toggle(id)// here is the function which gets the different ids of the div
{
var element = document.getElementById(id);
if(element.style.display == "none")
{
element.style.display = "block";
}
else
{
element.style.display = "none"
}
}
document.getElementById returns a single object and not an array.
If you want to get both the divs, I suggest using a class to get them.
If you wanted to only show one at a time, for example if you were building a tabs, then you could use this code to hide all the other divs first, then show only the one you want to toggle. Otherwise, if you're happy to toggle them, you can use the code posted by the others.
JS Fiddle demo: http://jsfiddle.net/ecs77e9a/
HTML
<p onclick="toggle('div1');">Sentence1</p>
<p onclick="toggle('div2');">Sentence2</p>
<div id="content">
<div id="div1" name="Name 1" style="display:none; width:400px; height:300px; border:1px solid black; background-color:yellow;" id="div1">Barun Ghatak</div>
<div id="div2" style="display:none; width:400px; height:300px; border:1px solid black; background-color:black;" id="div2">Bhoopi</div>
</div>
JS
function toggle(id)
{
//Hide all other divs first
var divs = document.getElementById('content').childNodes;
for ( var i = 0; i < divs.length; i++ ) {
if ( divs[i].nodeName == "DIV" ) {
var div = document.getElementById(divs[i].id);
div.style.display = "none";
}
}
//Show the one that's being requested
var element = document.getElementById(id);
element.style.display = "block";
}

event handler in javascript

I have this snippet, What I want to do is when you onclick the div it will not be affected by the mouseover and mouseout.. thank you very much for all your help..
<div id="div" onmouseover="over_div()" onmouseout="out_div()" onclick="click_div()" style="width:100px; height:100px; border:2px solid black"></div>
<script>
function click_div(){
document.getElementById("div").style.backgroundColor="red";
}
function over_div(){
document.getElementById("div").style.backgroundColor="green";
}
function out_div(){
document.getElementById("div").style.backgroundColor="white";
}
</script>
You could do something like this:
<div id="div" onmouseover="over_div()" onmouseout="out_div()" onclick="click_div()" style="width:100px; height:100px; border:2px solid black"></div>
<script type="text/javascript">
var isClicked = false;
function click_div(){
isClicked = true;
document.getElementById("div").style.backgroundColor="red";
}
function over_div(){
if(!isClicked )
document.getElementById("div").style.backgroundColor="green";
}
function out_div(){
if(!isClicked )
document.getElementById("div").style.backgroundColor="white";
isClicked = false;
}
</script>
However, using global variable is a bad practice. If you understand the concept of closure, you can use something like this instead :
<div id="div" style="width:100px; height:100px; border:2px solid black"></div>
<script type="text/javascript">
(function()
{
var div = document.getElementById("div");
var isClicked = false;
div.addEventListener("click", function() {
div.style.backgroundColor = "red";
isClicked = true;
});
div.addEventListener("mouseover", function() {
if(!isClicked)
div.style.backgroundColor = "green";
});
div .addEventListener("mouseout", function() {
if(!isClicked)
div.style.backgroundColor = "white";
isClicked = false;
});
}
)();
</script>
Using this, the div and isClicked variables won't be in conflicted with other variable that could have the same name later in your code.
You can't achieve this with events added to the tag of the element. Here is a jsfiddle which works as you want:
http://jsfiddle.net/krasimir/Ru5E5/
Javascript:
var element = document.getElementById("div");
var isClicked = false;
element.addEventListener("click", function() {
isClicked = true;
element.style.backgroundColor="red";
});
element.addEventListener("mouseover", function() {
if(isClicked) return;
element.style.backgroundColor="green";
});
element.addEventListener("mouseout", function() {
if(isClicked) return;
element.style.backgroundColor="white";
});
HTML
<div id="div" style="width:100px; height:100px; border:2px solid black"></div>
Set a global flag up and when you do your on click event set it to 1. In your mouse out event test to see if flag is 1. If it is then don't change the background colour.
If you want the onMouseOver and onMouseOut events to be completely disabled, you can also remove the event handlers from them by adding only two lines of code.
<div id="div" onmouseover="over_div()" onmouseout="out_div()" onclick="click_div()" style="width:100px; height:100px; border:2px solid black"></div>
<script>
function click_div(){
document.getElementById("div").style.backgroundColor="red";
// Disable the other two events
document.getElementById("div").onmouseover=null;
document.getElementById("div").onmouseout=null;
}
function over_div(){
document.getElementById("div").style.backgroundColor="green";
}
function out_div(){
document.getElementById("div").style.backgroundColor="white";
}
</script>

Categories