I searched in this community, answers are available but does not work for my code.
Although my code works when I use button OnClick but I don't want to load it from within the body.Please help to load this JavaScript code automatically as soon as window load.
<html lang="en">
<head><title>demo</title>
<script>
function removeElement(parentDiv, childDiv){
//if (childDiv == parentDiv) { alert("The parent div cannot be removed.");}
if (document.getElementById(childDiv)) {
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child); //parent.remove(parentDiv);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
};
</script>
</head>
<body> <!-- I don't want to load it in body onLoad="removeElement('parent','child');" -->
<div id="parent" style="border: 1px solid red; padding: 10px;">
I am the parent div.
<div id="child" style="border: 1px solid green; padding: 10px;">
I am a child div within the parent div.
</div>
</div>
<input type="button" value="Remove Element" onClick="removeElement('parent','child');">
</body>
</html>
If you wrap you code in a 'DOM ready event'
$(function() {
// your code here
}
That is the short handed version, alternatively you can use:
$( document ).ready(function() {
// your code here
}
Note: your question has the 'jquery' tag so, you should reference this on your file also if you wish to utilise this library, for example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
Just add window.onload = function() { removeElement('parent','child'); } before </script>
Related
I am trying to dynamically add a div to parent div when a button is clicked.But once it is created another same child div should not be created again when the button is clicked. So this is what I tried to do
$("#b1").click(function(){
$("#d1").has("#d2").remove($(this));
$("#d1").append($("<div>",{id:"d2",text:"Dynamically added Second DIV"}));
});
It is working but I am getting "TypeError: expr.replace is not a function" in the console...Please suggest.
Thank you...
You can check children.length to find if a child exist
$("#b1").click(function() {
if ($("#d1").children("#d2").length <= 0) {
console.log(1)
$("#d1").append($("<div>", {
id: "d2",
text: "Dynamically added Second DIV"
}));
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d1">Paremt Dom</div>
<button id="b1">Click</button>
It seems like you want to remove your button #b1 when you've clicked it once. Why not just remove it and add the element when the button is clicked? Like this:
$("#b1").click(function(){
$(this).remove();
$("#d1").append($("<div>",{id:"d2",text:"Dynamically added Second DIV"}));
});
#d1{
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d1"></div>
<button id="b1">Button</button>
If you really want to see if an element with id d2 exists within d1 you can do that with the following if-statement:
if ($('#d1').find('#d2').length) {
// Element found
}
With that method, you can do another variant where the button isn't removed but won't work after one element is created:
$("#b1").click(function(){
if (!$('#d1').find('#d2').length) {
$("#d1").append($("<div>",{id:"d2",text:"Dynamically added Second DIV"}));
}
});
#d1{
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d1"></div>
<button id="b1">Button</button>
function addElement() {
var parent = $('#container')["0"];
var elem = document.createElement('div');
elem.setAttribute('id', 'child');
var text = document.createTextNode("child");
elem.append(text);
if(!parent.children.length > 0) {
parent.append(elem);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">Parent</div>
<button type="button" id="button" onclick="addElement();">Click</button>
<html>
<head>
<style>
#container {position:relative;left:15%;}
#myImage {width:65%;height:280px;}
#text {padding-top: 50px;}
#textbox {width:65%;height:280px;position:absolute;top:0;left:0;}
</style>
</head>
<body>
<div id="container" onclick="changeImage()" >
<img id="myImage" src="C:\Documents and Settings\svarghe1\My Documents\Downloads\Jaguar_Xj_Saloon_4.jpgj_.jpg" alt="">
<div id="textbox">
<p style="color:white;text-align:center;margin-top:50px;"class="text">Jaguar_Xj_Saloon</p>
<script>
function changeImage() {
if (document.getElelmentById("container").innerHTML="myImage") {
container.appendChild(myImage)
} else {
container.appendChild(textbox)
}
}
</script>
</div>
</div>
</body>
</html>
Here, I am trying to create a script for Sharepoint site page to change an element in div from Image to textbox with Onclick or hover property. There might be a lot of mistakes as this is my first attempt on JS. I have also tried
<script>
function changeImage() {
var image= document.getElementById("myImage");
if (image=true) {
var element = document.getElementById("container");
var UImage = document.createElementById("myImage");
element.appendChild(UImage)
} else {
var element = document.getElementById("container");
var Utextbox = document.createElementById("textbox");
element.appendChild(UImage)
element.appendChild(Utextbox);
}
}
</script>
#container:hover #myImage{ display:none; }
I have tried the code above in CSS, instead of script. It didn't work. At the same time the code,
a:hover #box{ text-decoration: none;color:green;background-color: Turquoise;cursor:pointer }
Works really fine. Why is that? I have given class instead of id. It also didn't work. It works in ordinary HTML file. But can't get to work in Sharepoint site.
So, can you help?
Instead of appending Image and text box from the javascript, you can already write the html codes for both and do the hide/show according to your need. I think it will make things lot easier and neat.
As for the Hover property, you can attach event of hover with jquery.
You can check the following link: http://api.jquery.com/hover/
I'm learning JavaScript and jQuery. What am I doing wrong here? It will create window but not insert text. Thank you for your help
Script:
$(document).ready(function(){
$('.button7').click(function(){
$('#page').append('<div id="window"></div>');
$("#window").load("pages/window1.html");
});
});
HTML:
<div class="window1">
<p style="color: white">HELLO WORLD!</p>
</div>
next problem is that it dont want to load html file
$(document).ready(function() {
$('.button7').click(function() {
$('#page').append('<div id="window">NEW DIV ADDED</div>');
$("#page").find("div").on("ondivload", function() {
$("#window").load("window1.html", function() {
alert("now external html loaded");
});
});
alert("now div#window appended");
$("#page").find("div").trigger("ondivload");
});
});
You can use .html() and .text() to insert html and text content respectively to target control/element. And also you can use .load() to get content of external html file to control.- Note: this will be a GET request to external file and it has callback convention.
.html and load example. Click html to append a div with id = window and after appending , it will load html into that div window.
$(document).ready(function() {
$('#btn').click(function() {
$('.page').append('<div id="window">NEW DIV ADDED</div>');
$(".page").find("div").on("ondivload", function() {
$("#window").load("http://www.w3.org/TR/html4/index/elements.html", function() {
alert("now external html loaded");
});
});
alert("now div#window appended");
$(".page").find("div").trigger("ondivload");
});
});
.page {
border: 5px #CCC solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="HTML" id="btn" />
<div class="page">
OLD Content
</div>
You can simply use the .html() method which get the HTML contents of the first element in the set of elements.
If you want to insert just text you can use the function .text().
You have this: <p style="color: white">HELLO WORLD!</p>
Unless your background color is not white, change the color to any color other than white if you want to see the text. color is to change text color.
Also, you've not added .button7 and #page to the HTML
DEMO
I've probably been browsing the wrong search words while trying to look for the answer to this problem, but all I find are jQuery solutions.
What I'm trying to achieve is by the click of different buttons, is to change the content of a "container" div, with the corresponding div content that you click the button for.
I feel like my javascript in this jsfiddle is not sufficient, but it's all I could come up with from my browsing.
HTML
<div id="content">
<div id="work1" class="work">Content 1</div>
<div id="work2" class="work">Content 2</div>
</div>
<input type="button" onclick="changeContent('work1');" value="work 1"/>
<input type="button" onclick="changeContent('work2');" value="work 2"/>
CSS
#content{
height:500px;
width:500px;
border:1px solid #000;
}
Javascript
function changeContent(){
document.getElementById('content').innerHTML = document.getElementByClassName('work');
}
I'm using classes because I thought it would cut down on the javascript needed?
document.getElementByClassName('work');
Supposed to be
document.getElementsByClassName('work'); // check the missing s
And this returns a live node list. If the ClassName for each is unique then you may directly use the first element
document.getElementByClassName('work')[0].innerHTML;
Also it is better idea to bind events in javascript rather than assigning the inline event attribute.
function changeContent(id){
var elems = document.getElementsByClassName('work'); //get elements with the class
for (var i=0;i<elems.length;i++) { //loop through them all
elems[i].style.display = "none"; //set display to none to hide them
}
document.getElementById(id).style.display="block"; //find the element passed in and show it
}
if what i understand is correct, you are trying to show/hide content based on a click on a specific button
Try this
<!DOCTYPE html>
<html>
<head>
<style>
#content{
height:500px;
width:500px;
border:1px solid #000;
}
</style>
<script language = "javascript">
function showContent(value)
{
if(value == 'work1'){
document.getElementById('work2').style.visibility = "hidden";
document.getElementById('work1').style.visibility = "visible";
}
else{
document.getElementById('work2').style.visibility = "visible";
document.getElementById('work1').style.visibility = "hidden";
}
}
</script>
</head>
<body>
<div id="content">
<div id="work1" class="work">Content 1</div>
<div id="work2" class="work">Content 2</div>
</div>
<input type="button" onclick="showContent('work1');" value="show work 1"/>
<input type="button" onclick="showContent('work2');" value="show work 2"/>
</body>
</html>
Do you know how to create a form with edit mode? For details: Suppose I've a form with 5 or 6 fields which has button 'Save' and 'Cancel' . If I save the form, it'll show the plain form without text fields and a button named 'Edit' will appear. And When I'll click on 'edit', the form will be editable. Is it possible?
Full example, can handle as many input fileds as you want.(no select,textarea..)
The code is written based on modern browsers in pure javascript and css3.
Tested on Chrome.
hides and shows the buttons with css3,
saves the default values to apply them on cancel,
responds on the enter button.
If any questions .. just ask
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Modern Form</title>
<style>
label{display:block;}
form input{border:none;outline:none;box-sizing:border-box;}
form.invert input{border:1px solid rgba(0,0,0,0.2);outline:none;}
form>button:nth-of-type(1){
color:green;display:none;
}
form>button:nth-of-type(2){
color:red;display:none;
}
form>button:nth-of-type(3){
color:yellow;display:inline-block;
}
form.invert>button:nth-of-type(1){
display:inline-block;
}
form.invert>button:nth-of-type(2){
display:inline-block;
}
form.invert>button:nth-of-type(3){
display:none;
}
</style>
<script>
(function(W){
var D,form,bts,ipt;
function init(){
D=W.document,previous=[];
form=D.getElementsByTagName('form')[0];
bts=form.getElementsByTagName('button');
ipt=form.getElementsByTagName('input');
form.addEventListener('submit',save,false);
bts[1].addEventListener('click',cancel,false);
bts[2].addEventListener('click',edit,false);
}
function save(e){
e.preventDefault();
form.classList.remove('invert');
var l=ipt.length;
while(l--){
ipt[l].readOnly=true;
};
previous=[];
//send your info here
}
function edit(e){
e.preventDefault();
form.classList.add('invert');
var l=ipt.length;
while(l--){
previous[l]=ipt[l].value;
ipt[l].readOnly=false;
}
}
function cancel(e){
form.classList.remove('invert');
e.preventDefault();
var l=ipt.length;
while(l--){
ipt[l].value=previous[l];
ipt[l].readOnly=true;
}
}
W.addEventListener('load',init,false);
})(window)
</script>
</head>
<body>
<form>
<label>A:<input readonly></label>
<label>B:<input readonly></label>
<label>C:<input readonly></label>
<button>Save</button><button>Cancel</button><button>Edit</button>
</form>
</body>
</html>
ps: the handler function could be merged into one bigger function... but i think this way it's easier to understand
The following is a very simplistic sample of how this might be done.
It is just to give you an idea - there are many ways to approach this.
Works in chrome, completely untested in other browsers (for example: assumes 2 pixel border)
What you do will depend on your UX and browser requirements
Sample Fiddle
HTML
<span>Example</span>
<div class="example">
<form>
<label for="ex1fld1">Field 1:</label><input type="text" name="ex1fld1" readonly value="Hello"></input>
<label for="ex1fld2">Field 2:</label><input type="text" name="ex1fld2" readonly></input>
<input type="button" value="Edit"></inpu>
</form>
</div>
CSS
div {
margin-bottom: 20px;
margin-top: 10px;
}
input[type="text"] {
font-size: 14px;
}
input[type="text"][readonly] {
border: 2px solid rgba(0,0,0,0);
}
Script (jQuery used here, but not required for something like this)
var readonly = true;
$('.example input[type="button"]').on('click', function() {
$('.example input[type="text"]').attr('readonly', !readonly);
readonly = !readonly;
$('.example input[type="button"]').val( readonly ? 'Edit' : 'Save' );
return false;
});