The code below does not appear to function properly. newH2Text should replace para1. This does not happen. I used Sublime, then looked through the browser console, and even on SO's code snippet. I am almost certain I have the code verbatim.
The first paragraph, which has its own id attribute should be replaced by newH2Text which is created in my JS script. I can't find my mistake here. Please help.
PS the refresh button works properly. No issue there.
function replaceHeading(){
var newH2=document.createElement("h2");
var newH2Text=document.createTextNode("Welcome");
newH2.appendChild(newH2Text);
var myDiv=document.getElementById("id1");
var oldP=document.getElementById("para1");
myDiv.replaceChild(NewH2,oldP);
}
window.onload=function() {
document.getElementById("btn").onclick=replaceHeading;
}
<div id="id1">
<p id="para1">Welcome to my web page.</p>
<p id="para2">Take a look around.</p>
<input type="button" id="btn" value="Replace Element">
<br>
<input type="button" value="refresh" onclick="location.reload()">
</div>
NewH2 is capitalized but should be newH2 with a lowercase.
myDiv.replaceChild(newH2,oldP);
See this fiddle for an example
Update
To catch these errors earlier you can use "strict mode". An example of this would be:
;(function(){
"use strict";
function replaceHeading(){
var newH2=document.createElement("h2");
var newH2Text=document.createTextNode("Welcome");
newH2.appendChild(newH2Text);
var myDiv=document.getElementById("id1");
var oldP=document.getElementById("para1");
myDiv.replaceChild(NewH2,oldP);
}
}());
Which would give you the error Uncaught ReferenceError: NewH2 is not defined.
There are at least two different ways todo what you are trying:
function replaceHeading(){
/***** CORRECTED AND WORKING
var newH2=document.createElement("h2");
var newH2Text=document.createTextNode("Welcome");
newH2.appendChild(newH2Text);
var oldP=document.getElementById("para1");
document.getElementById("id1").replaceChild(newH2,oldP);
*////
// OR a more simpler way
document.getElementById("para1").innerHTML = "<h2>Welcome</h2>";
}
window.onload=function() {
document.getElementById("btn").onclick=replaceHeading;
}
<div id="id1">
<p id="para1">Welcome to my web page.</p>
<p id="para2">Take a look around.</p>
<input type="button" id="btn" value="Replace Element">
<br>
<input type="button" value="refresh" onclick="location.reload()">
</div>
Related
When I make a page, I'm stucking in caching problem. Here is my simplified code.
[HTML]
<body>
<div>here parent contents</div>
<input id="btn1" class="btn" data-val="1" type="button" />
<input id="btn2" class="btn" data-val="2" type="button" />
<input id="btn3" class="btn" data-val="3" type="button" />
<div id="childContents"></div>
</body>
[javascript]
$(".btn").click(function (e) {
$("#childContents").load("url?val=" + e.getAttribute("data-val"),
function () {
success call back function
});
});
And the point is that :
[Child Html]
<!-- the image change depanding on some condition -->
<div style="background-image: url('imgUrl')">
contents
</div>
Whenever I click button and reload the child view, I hope the image, which child view has, change.
But since the cached image, the child's image does not change. How can I do for it?
I want to solve it with javascript, since sometimes the jquery version become a big problem and I always consider the version of it. So I want to make my code of small dependance on jQuery. (eg. jquery’s async ajax’s option and so on is not working lower version of IE)
You can add the current time as a cache breaker.
$(".btn").click(function (e) {
$("#childContents").load("url?val=" + e.getAttribute("data-val"),
function () {
//get time since 1970 in milliseonds
var d = new Date();
var n = d.UTC();
//append a cache breaker
var imgUrl = "background.jpg" + "?t=" + n;
//set the img url
$('#backgrounddiv').css('background-image', 'url("'+imgUrl+'")');
});
});
<div id="backgrounddiv" style="background-image: url('background.jpg')">
contents
</div>
this is actually a follow up question to this question
that was solved thanks to Rory McCrossan.
I now have this functioning script; a search function that shows a div depending on a searchword.
JS
$('#search').click(function() {
var txt = $('#search-criteria').val();
if (txt)
$('.fruit').hide().filter('#' + txt.toLowerCase()).show();
});
CSS
.fruit {
display: none;
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div class="fruit" id="apple">
<h3>Some text about apples</h3>
</div>
<div class="fruit" id="orange">
<h3>Some text about oranges</h3>
</div>
What I now wonder is if someone could help me with some kind of error handling to add to this script, preferably that can be smoothly added without rewriting the logic of the script. I.e. I'd like to display another div with a message when the search comes up with no result and/or when the user makes an empty string search.
Since I'm actually an UX designer my technical skills are somewhat limited and I'm therefore very grateful if someone could help me with this...
Thanks in advance!
simple javascipt error handing using try and catch:--
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function adddlert2($a){
alert($a);
}
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
You can use try and catch in this case, but If you want to be informed about all irregularities in your application I prefer to use dedicated services for this job.
I use Sentry.io, this is nice service to handle exceptions and errors in backend and frontend. Is simple to use, you only need to add one additional JS script without modifying existing code. More about installation process here
I guess what you're looking for is this :) I know changing to .keyup() had nothing to do with your question, so change it back if you like
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div id="default" class="fruit">
no fruit found
</div>
<div class="fruit" id="apple">
<h3>Some text about apples</h3>
</div>
<div class="fruit" id="orange">
<h3>Some text about oranges</h3>
</div>
and
<script>
$(document).ready(function(){
$('#search-criteria').keyup(function() {
var txt = $('#search-criteria').val();
if (txt){
var elements = $('.fruit').hide().filter('#' + txt.toLowerCase());
if(elements.length > 0){
elements.show();
}
else{
$("#default").html("No result found for "+txt);
$("#default").show();
setTimeout(function(){
$("#default").hide();
}, 1000);
}
}
});
});
</script>
Another error handing(javascript example) using javascript SEARCH function:--
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
try {
var str_wrong = "Visit";
var n = str.search("Visit");
document.getElementById("demo").innerHTML = n;
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
I have written a code to show or hide a picture based on the value of corresponding checkboxes. I was able to have the picture shown or hidden on reload if 'checked="checked"' is written into the checkbox.
I was able to write a code to save the value of the checkbox but then the picture is no longer tethered to the checked/unchecked value and changes with reload.
My end goal is to have the a checked checkbox to show the picture and unchecked checkbox to hide the picture and I need the value saved to allow the correct value to work on reload after a change has been made.
This is just a small snip of the overall code. The whole thing is a series of 64 checkboxes linked to 64 different pictures, which overlay a mapped background image.
I should also mention that this will ultimately be used for a SharePoint site, if that makes a difference.
Thanks in advance for any help!!
(There is a link to jsfiddle demo at the bottom)
HTML:
<a href="home.aspx">
<p id="A1R1" style="left:146px;top:256px;position:absolute;z-index:inherit;" class="hidden">
<img id="A1R1" alt="A1R1" src="red.jpg" width="108" height="60" />
</p>
</a>
<a href="home2.aspx">
<p id="A2R2" style="left:273px;top:256px;position:absolute;z-index:inherit;" class="hidden">
<img id="A2R2" alt="A2R2" src="green.html" width="108" height="60" />
</p>
</a>
<fieldset class="fieldset-auto-width" style="width:165px">
<center>
<p style="font-size:25px">Show/Hide</p>
</center>
<fieldset class="fieldset-auto-width" style="width:150px">
<center>A1 Green/Red
<p>
</center>
<center>
<input type="checkbox" id="A1G" checked="checked" /> </center>
</fieldset>
<fieldset class="fieldset-auto-width" style="width:150px">
<center>A2 Green/Red
<p>
</center>
<center>
<input type="checkbox" id="A2G" checked="checked" /> </center>
</fieldset>
</fieldset>
<center>
<input type="button" id="ReserveerButton1" value="save" onclick="save()" />
<input type="button" id="Wisbutton1" value="delete" onclick="wis()" />
</center>
JQUERY:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
(function(i, $) {
var $A_1_G = $('#A1G'),
$A_1_R_1 = $('#A1R1');
var toggleMain = function() {
$A_1_R_1.slideToggle();
};
if ($A_1_G.is(':checked')) {
toggleMain();
}
$A_1_G.on('click', toggleMain);
})(document, jQuery);
(function(i, $) {
var $A_2_G = $('#A2G'),
$A_2_R_2 = $('#A2R2');
var toggleMain = function() {
$A_2_R_2.slideToggle();
};
if ($A_2_G.is(':checked')) {
toggleMain();
}
$A_2_G.on('click', toggleMain);
})(document, jQuery);
</script>
Javascript:
function save() {
var checkbox = document.getElementById('A1G');
localStorage.setItem('A1G', checkbox.checked);
var checkbox = document.getElementById('A2G');
localStorage.setItem('A2G', checkbox.checked);
}
function load() {
var checked = JSON.parse(localStorage.getItem('A1G'));
document.getElementById("A1G").checked = checked;
var checked = JSON.parse(localStorage.getItem('A2G'));
document.getElementById("A2G").checked = checked;
}
function wis() {
location.reload();
localStorage.clear()
}
load();
Link to fiddle code
This seems to take care of it: http://jsfiddle.net/w0yL5njs/
Move your 'toggleMain w/ jQuery' code block to after your 'save/load' code block, so that the checkboxes will be pre-checked before the images' initial visibility are set.
So the order of your <script> tags will be
a) <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
b) The script that uses jQuery.
c) your save/load script that doesn't use jQuery.
Actually, (b) and (c) can be in the same <script> but (a) must be separate.
Add display:none to the <p> containing the images.
Is that what class="hidden" was intended to do? You could add .hidden { display: none; } to your CSS...
// Remove
if ($A_1_G.is(':checked')) {
toggleMain();
}
// ADD
if ($A_1_G.is(':checked')) {
$A_1_R_1.show();
}else{
$A_1_R_1.hide();
}
//remove
if ($A_2_G.is(':checked')) {
toggleMain();
}
if ($A_2_G.is(':checked')) {
$A_2_G.show();
}else{
$A_2_G.hide();
}
I am getting this error in IE 11 but no other browsers, seems like simple code but maybe I am missing something? Below is a sample of the code. Note I can replace parent. with the selector and it works fine.
$('.hs-search input[type="submit"]').click(function(){
parent = $('.header-search');
if(parent.hasClass('active')){
return true;
}else{
parent.addClass('active');
return false;
}
});
And here is a sample of the garbage markup being generated.
<div class="header-search">
<div class="hs-search">
<div id="ctl00_header1_SearchInput1_pnlSearch" class="searchpanel " onkeypress="javascript:return WebForm_FireDefaultButton(event, 'ctl00_header1_SearchInput1_btnSearch')" style="display:inline;">
<input onfocus="javascript:watermarkEnter(this, 'Search');" onblur="javascript:watermarkLeave(this, 'Search');" name="ctl00$header1$SearchInput1$txtSearch" type="text" id="ctl00_header1_SearchInput1_txtSearch" title="Site Search" class=" " style="display: none;">
<input type="submit" name="ctl00$header1$SearchInput1$btnSearch" value="search" id="ctl00_header1_SearchInput1_btnSearch">
</div>
</div>
</div>
With this code:
parent = $('.header-search');
'parent' actually refers to the Window object because it bubbles up to the global scope.
Define it this way:
var parent = $('.header-search');
and it is then confined to the local scope and should work as you expect it to.
I am new to the site (and coding) so please bear with me!
I am trying to add the following clickable slideshow to my site in a way that means I can change the images in one file (HTML or JS) and this be reflected on every page on which the slideshow is called:
<table border="0" cellpadding="0">
<td width="100%">
<img src="image1.bmp" width="200" height="200" name="photoslider"></td>
</tr>
<tr>
<td width="100%">
<form method="POST" name="rotater">
<div align="center">
<center><p>
<script language="JavaScript1.1">
var photos=new Array()
var text=new Array()
var which=0
var what=0
photos[0]="image1.bmp"
photos[1]="image2.bmp"
photos[2]="image3.bmp"
text[0]="Image One"
text[1]="Image Two"
text[2]="Image Three"
window.onload=new Function("document.rotater.description.value=text[0]")
function backward(){
if (which>0){
window.status=''
which--
document.images.photoslider.src=photos[which];
what--
document.rotater.description.value=text[what];
}
}
function forward(){
if (which<photos.length-1){
which++
document.images.photoslider.src=photos[which]
what++
document.rotater.description.value=text[what];
}
else window.status='End of gallery'
}
function type()
{
alert("This textbox will only display default comments")
}
</script>
<p><input type="text" name="description" style="width:200px" size="50">
<p><input type="button" value="<<Back" name="B2"
onClick="backward()"> <input type="button" value="Next>>" name="B1"
onClick="forward()"><br />
</p>
</center>
</div>
</form>
</td>
</tr>
Currently I have used:
<script type="text/javascript" src="images.js"></script>
in the relevant html div. to call a simple .js file which displays the images in one long list, e.g.
document.write('<p>Image One</p>')
document.write('<img src="image1small.png" alt=Image One; style=border-radius:25px>')
document.write('<p>Image Two</p>')
document.write('<img src="image2small.png" alt=Image Two; style=border-radius:25px>')
I have tried every way I can think of, and searched many posts on here to try and get the slideshow to display within the same div. I have copied the html code into the .js file and appended it with document.write on every line, I have tried / on every line, I have tried 'gettingdocument.getElementById', but nothing works!
The slideshow code itself is fine; if I put this directly onto each page then it works correctly, I just can't seem to 'link' to this code and have it run so anything appears.
Please provide the simplest possible solution for this, without any need to install jquery plugins, or use anything other than basic HTML and JS.
There were alot of small bugs, i fixed them for you. you didn't put a semicolon after your javascript statements, tey aren't neccesary but it's cleaner code, you didn't exit alot of html tags
<table border="0" cellpadding="0">
<tr>
<td width="100%">
<img src="image1.bmp" width="200" height="200" name="photoslider">
</td>
</tr>
<tr>
<td width="100%">
<form method="POST" name="rotater">
<div align="center">
<center>
<p>
<p id="description" style="width:200px" size="50"></p>
<p><a onClick="backward()"><img src="imageback.png" alt="back" />Back Image</a>
<p><a onClick="forward()"><img src="forward.png" alt="forward" />Forward Image</a>
</p>
</center>
</div>
</form>
</td>
</tr>
Javascript:
(function() {
var photos=[];
var text= [];
var which=0;
var what=0;
photos[0]="image1.bmp";
photos[1]="image2.bmp";
photos[2]="image3.bmp";
text[0]="Image One";
text[1]="Image Two";
text[2]="Image Three";
document.getElementById('description').innerHTML = text[0]
backward = function(){
if (which>0){
which--;
window.status='';
what--;
console.log(which);
document.images.photoslider.src=photos[which];
document.getElementById('description').innerHTML = text[what];
}
}
forward = function(){
if (which < (photos.length-1)){
which++;
console.log(which);
document.images.photoslider.src=photos[which];
what++;
document.getElementById('description').innerHTML = text[what];
}
else {
document.getElementById('description').innerHTML = 'End of gallery';
}
}
function type()
{
alert("This textbox will only display default comments")
}
})();
And last but not least i've created the fiddle to show you it's working:
http://jsfiddle.net/45nobcmm/24/
You can create a javascript file that search for an element and change the innerHTML of the element to the slideshow you want to show.
For example this could be the script:
var slideshow = document.getElementById('slideshow');
slideshow.innerHTML = 'Your slideshow html';
and your main html page should have a slideshow div.
but you need to know that it's not the best solution, you should learn PHP or another back-end language and than you could use include('page.html'); for example