Do the exact contrary of append in Jquery - javascript

I'm working on a 3D interface with Babylonjs, so I need a canvas. Around that canvas I want to implement html elements (with Holy grail layout : nav to the left, main which is canvas at the middle and aside to the right) according to 2 modes : visualisation and edition.
I have a script to handle the canvas and play with babylonjs functions, and another one to manage the construction of the html according to the chosen mode.
As you can see in my code, I assign my html code to a variable, and append that variable to my holygrail main. However, I don't want my canvas to be recreated each time I change mode, so I implemented it directly in the HTML, it's constant.
My problem is : I want to append elements to my div #insertHere, but also to remove all the elements (excepted my canvas which has to remain) of this #insert div before appending new ones (else I would have several navs and asides).
Can anyone help me ?
Thank for your time !
Here's my construction script :
var content = "";
var construct = true;
var visualize = false;
function Create(){
content = "";
if(construct == true && visualize == false){
content += "<div id='1'> <p> hello</p></div><div><p>Insert a lot of html here</p></div>";
$("insertHere").append(content);
}
if(construct == false && visualize == true){
content += "<div id='not1'><p> Definitely not the same content as the construct one</p></div>";
$("insertHere").append(content);
}
}
$(window).ready(function(){
Create();
$("#switchmode").click(function(){
construct = !construct;
visualize = !visualize;
// INSERT THE SOLUTION TO CLEAR THE HTML HERE
CreationPage();
});
});
And here's my HTML (both are short representation of what I really have) :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
</head>
<body id="body" class="HolyGrail">
<header>
<link rel="stylesheet" type="text/css" href="style.css" media="all">
<link rel="stylesheet" href=".\bootstrap\css\bootstrap.css">
<link rel="stylesheet" href="justcontext.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" defer></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<script style="text/javascript" src="scripts/construction.js" defer></script>
</header>
<div id='menuonglets' class='btn-group' role='group' aria-label='Basic example'>
<button type='button' class='btn btn-secondary' id='switchmode'>Mode Visu/ Mode Constru</button>
</div>
<div class='HolyGrail-body' id='insertHere'>
<main class='HolyGrail-content'>
<canvas id='renderCanvas'></canvas>
</main>
<!-- Things are inserted here -->
</div>
</body>
</html>

You could use jQuery's filter() function to remove all elements but the canvas.
Here's a working example:
$("#btn_clear").on("click", function(e){
e.preventDefault();
$("#insertHere").children().filter(":not(.HolyGrail-content)").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='HolyGrail-body' id='insertHere'>
<main class='HolyGrail-content' style="background: orange;">
<canvas id='renderCanvas'></canvas>
</main>
<p>I'm a paragraph</p>
<ul>
<li>Foo</li>
<li>bar</li>
</ul>
</div>
Remove all elements but the canvas
So:
$(window).ready(function(){
Create();
$("#switchmode").click(function(){
construct = !construct;
visualize = !visualize;
// Remove all elements, except for the canvas and its container.
$("#insertHere").children().filter(":not(.HolyGrail-content)").remove();
CreationPage();
});
});

Related

Trying to add image changer in js

My goal is to have the image switch once it's been clicked and back again to the original image once the second image has been clicked again. I hope that makes sense. I've been trying this for two days with no success. Any help would be appreciated.
/* global document */
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg')
}
}
<head> <!-- Content in the head element will not be displayed by browers-->
<meta charset="utf-8">
<title> My Sample webpage</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<link href="stylesheets/mystyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Hello World !</h1> <!-- the size can be changed with css-->
<!-- <p class="para">It's a start of a new day</p>-->
<img src="images/cactus.jpg" alt="cactus">
<p class="para">Let us try to be</p>
<ul>
<!-- this is an unordered list-->
<li> Kind</li>
<li> Time</li>
<li> Why</li>
<li> Who</li>
</ul>
<p id="quote">The plan is to create a site that looks like this one, which was created by a popular mystery writier.</p>
<!-- <script>
var myHeading = document.querySelector("h1")
myHeading.textContent = 'Be Kind' ;
</script> -->
</body>
I have fixed your code. There is one error in your code i.e., you haven't mentioned the file extension whether its in .jpg or any other format in setAttribute. So let's say if your old-typewriter is in jpg format than this code will work if you have another format of image just replace jpg with that format and try to rerun this code.
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter.jpg');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg')
}
}
I have edited complete code and you can replace your code with below code. It will work.
<!DOCTYPE html>
<html lang="en">
<head> <!-- Content in the head element will not be displayed by browers-->
<meta charset="utf-8">
<title> My Sample webpage</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<link href="stylesheets/mystyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Hello World !</h1> <!-- the size can be changed with css-->
<!-- <p class="para">It's a start of a new day</p>-->
<img src="images/cactus.jpg" alt="cactus">
<p class="para">Let us try to be</p>
<ul>
<!-- this is an unordered list-->
<li> Kind</li>
<li> Time</li>
<li> Why</li>
<li> Who</li>
</ul>
<p id="quote">The plan is to create a site that looks like this one, which was created by a popular mystery writier.</p>
</body>
<script>
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter.jpg');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg');
}
}
</script>
</html>
Holy-moly! So I took "Vipul's" suggestion of wrapping the code in script> and embedding the code in my HTML file which I wasn't doing before and voila. I want to thank all of you for the suggestions made. I hope I can return the favor one day.
Best,
<head> <!-- Content in the head element will not be displayed by browers-->
<meta charset="utf-8">
<title> My Sample webpage</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<link href="stylesheets/mystyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Hello World !</h1> <!-- the size can be changed with css-->
<!-- <p class="para">It's a start of a new day</p>-->
<img src="images/cactus.jpg" alt="cactus">
<p class="para">Let us try to be</p>
<ul>
<!-- this is an unordered list-->
<li> Kind</li>
<li> Time</li>
<li> Why</li>
<li> Who</li>
</ul>
<p id="quote">The plan is to create a site that looks like this one, which was created by a popular mystery writier.</p>
<button>Change name</button>
<script src="scripts/myscripts.js"> </script>
<script>
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter.jpg');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg');
}
}
var myHeading = document.querySelector("h1")
myHeading.textContent = 'Be Kind' ;
-->
This code should work:
index.html
<!doctype html>
<html>
<head>
<title>My Test Page</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<a onclick="switchImg()">
<img src="img1.png" id="img">
</a>
</body>
</html>
script.js
var imgSrc = document.getElementById("img").src
function switchImg() {
if(imgSrc == "img1.png") {
document.getElementById("img").src = "img2.png";
imgSrc = document.getElementById("img").src;
}
}
Just replace the names of the image files.

Trying to use Javascript to change img src in HTML

I'm trying to use Javascript to change the src attribute of an image (id: big-img) to that of a smaller image (class: clicky) when the smaller image is clicked to create . Unfortunately it doesn't seem to be working. Code provided below.
HTML:
<!DOCTYPE HTML>
<html lang="en">
<head>
<!-- Always use meta tags in head first -->
<!-- Sets character encoding (utf-8 = unicode) -->
<meta charset="utf-8">
<!-- Sets width of the page to width of the device and sets initial zoom
value to 1.0. Used for mobile viewing -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Linking in bootstrap (css) and author styles. -->
<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="css/styles.css">
</head>
<body>
<!-- For simple Javascript concept exercises -->
<div id="practice">
<p>
Does this work?
</p>
</div>
<!-- For image related complex(ish) Javascript exercises -->
<div class="container">
<div class="row">
<div class="clicky col-md-3"><img src="img/img1.jpg"></div>
<div class="clicky col-md-3"><img src="img/img2.jpg"></div>
<div class="clicky col-md-3"><img src="img/img3.jpg"></div>
<div class="clicky col-md-3"><img src="img/img4.jpg"></div>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<img id="big-img"
class="large-img"
src="img/img1.jpg">
</div>
</div>
</div>
<!-- <div class="col-md-12">
<img id="bigImage"
class="large-img"
src="img_1.jpg"
alt="graffittied building"/>
</div> -->
<!-- Linking in Jquery library, bootstrap (JS) and my scripts. Imported in
that order due to bootstrap requiring some Jquery features so needs to be
lower in source order -->
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
</body>
</html>
Javascript:
$(".clicky").click(function(){
$("#big-img").attr('src',
$(this).attr('src'));
});
As clicky is not img element it doesn't have src attribute thus the code is working as expected.
You need to traverse to img element the fetch its attribute, there are various ways to achieve that. Here in code I have used .find() method since img is child of clicky element
$(".clicky").click(function(){
$("#big-img").attr('src', $(this).find('img').attr('src'));
});
OR, You can bind event with img element then your code will work
$(".clicky img").click(function(){
$("#big-img").attr('src', this.src);
//$("#big-img").attr('src', $(this).attr('src'));
});
function change_img(){
$(document).on("click",".clicky img",function(){
var el = $(this);
var src = $.trim(el.attr("src"));
(src !=="") ? $("#big-img").attr("src",src) : '';
});
}
$(function(){
change_img();
});
Try this:
$(".clicky").click(function(){
$("#big-img").attr('src',
$(this).find('img').attr('src'));
});
clicky class is attached to a div not to an img so it does not have a src attribute
What you can do is this:
$(".clicky > img").click(function(){
$("#big-img").attr('src', $(this).attr('src'));
});
But if you want to to attach the listener on the div, you can do this:
$(".clicky").click(function(){
$("#big-img").attr('src', $(this).find("img").attr('src'));
});
$(this) refers to the clicked element : <div>. You need to get img thats inside the div.
$(".clicky").click(function(){
$("#big-img").attr('src',$('img', this).attr('src'));
});
To complete :
$(".clicky").on('click', function(e){
$("#big-img").attr('src',$('img', this).attr('src'));
});

How to loop 3 divs with jQuery

I need a little help looping multiple divs (3 or more) using jQuery. The look I am after is having my home page rotate its main image div with other divs so that both the background image (of the div only) changes as well as links contained within the div.
I had created the effect with stacking CSS and fading in to an image behind, however now I also require the links in the div to change.
This is the HTML for the section -
<head>
<title>Sample</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.leanModal.min.js"></script>
<link type="text/css" rel="stylesheet" href="index.css" />
</head>
Now the Div that I want changing
<div class="jumbotron-1">
<div class="container">
<h1>What We Are</h1>
<p> A Paragraph</p>
<div class="divbutton">
Learn more
</div>
</div>
</div>
<div class="jumbotron-2">
<div class="container">
<h1>What We Are</h1>
<p> A Paragraph</p>
<div class="divbutton">
Learn more
</div>
</div>
</div>
<div class="jumbotron-3">
<div class="container">
<h1>What We Are</h1>
<p> A Paragraph</p>
<div class="divbutton">
Learn more
</div>
</div>
</div>
I found a similar code to what I am after :
var slideShowDivs = ['.jumbrotron-1', '.jumbotron-2', '.jumbotron-3'];
var currentID = 0;
var slideShowTimeout = 1000;
$(document).ready(function() {
for (var i = 1; i < slideShowDivs.length; i++) $(slideShowDivs[i]).hide();
setTimeout(slideShowChange, slideShowTimeout);
});
function slideShowChange() {
var nextID = currentID + 1;
if (nextID >= slideShowDivs.length) nextID = 0;
$(slideShowDivs[currentID]).stop(true).fadeOut(400);
$(slideShowDivs[nextID]).stop(true).fadeIn(400, function() {
setTimeout(slideShowChange, slideShowTimeout);
});
currentID = nextID;
}​
But it doesnt seem to work.
Any additional thoughts?
Try jquery each insted of for loop
$('.jumbrotron-1,.jumbotron-2,.jumbotron-3').each(function() {
$(this).hide();
setTimeout(slideShowChange, slideShowTimeout);
});
jsfiddle: http://jsfiddle.net/66Lz2xou/2/
or
$('div[class^="jumbrotron"]').each(function() {
$(this).hide();
setTimeout(slideShowChange, slideShowTimeout);
});
http://jsfiddle.net/66Lz2xou/3/
Sorry I need 50 reputation to comment, but I wanted to go off of #ARUN BERTILs answer.
You could put the divs in a array like:
var div_array = ['.jumbotron-1', '.jumbotron-2', '.jumbotron-3']
jQuery.each(div_array,function(i, val){
/* What you want each one to do*/
//example
$(val).css('background','blue');
})
Hi the best approach is to use this approach
$( "div" ).each(function( i ) {
//Your condition
} });
use class selectors
$(".jumbotron-1 .jumbotron-2 .jumbotron-3").each(function( i ) {
//process your code here
} });
or if you want child container divs attach > container to each of the selectors like .jumbotran-1 > container

Position of script tag in html

I am trying to duplicate Expanding Text Areas Made Elegant
Basically it explains how we can achieve something like fb comment box, where its size increases as text files the textarea.
I have this in my index.html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script src="test.js"></script>
</head>
<body>
<figure>
<div class="expandingArea">
<pre><span></span><br></pre>
<textarea></textarea>
</div>
</figure>
</body>
</html>
And my test.js looks like:
This doesn't really works.
However if I move everything inside the js file to a script tag inside body then it works fine. So my index file would look like:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
<figure>
<div class="expandingArea">
<pre><span></span><br></pre>
<textarea></textarea>
</div>
</figure>
<script>
function makeExpandingArea(container) {
var area = container.querySelector('textarea');
var span = container.querySelector('span');
if (area.addEventListener) {
area.addEventListener('input', function() {
span.textContent = area.value;
}, false);
span.textContent = area.value;
} else if (area.attachEvent) {
// IE8 compatibility
area.attachEvent('onpropertychange', function() {
span.innerText = area.value;
});
span.innerText = area.value;
}
// Enable extra CSS
container.className += ' active';
}var areas = document.querySelectorAll('.expandingArea');
var l = areas.length;while (l--) {
makeExpandingArea(areas[l]);
}
</script>
</body>
</html>
You're not actually using onload
Your formatting is so messed up it's hard to tell, but your init code is in a while loop at the bottom after your onload function.
When you include it in the <head> it runs before any elements exist. That's why the position of it matters.
In your browser(I recommend Chrome for testing) open up the developer tools(via right click and selecting inspect element) and make sure your test.js file's path is correct. Do this by selecting the 'Sources' tab on the top of the developer tools window and then selecting the test.js file on the list of sources.
I also consider it best practice to load your js files at the bottom of your web documents(before the last body tag) to guarantee they load AFTER your dom elements load.
try this in your code:
I have used inside a table andapply a css class "form-control". The properties of this text areas are in side tag in side
html code:
<html>
<body>
<table>
<tr>
<td>Description:</td>
<td><textarea name="DESCRIPTION" id="DESCRIPTION" class="form-control"></textarea></td>
<td></td>
</tr>
</table>
//css-code required inside html:
<style>
textarea.form-control {
height: auto;
resize: none;
width: 300px;
}
</style>
</body>
</html>

jQuery .insertAfter() copying input field values

I have created a html webpage here:
http://diagrams.inse1d.info/wbt.html
Code:
<!DOCTYPE html>
<html>
<head>
<title>WBT Charts</title>
<link rel="stylesheet" type="text/css" href="wbt.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="wbt.js"></script>
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,500,700' rel='stylesheet' type='text/css'>
</head>
<body>
<section>
<article>
<div id="wbtBlock">
<p>Press enter to save amendments</p>
<h1>Title of wbt:<input type="text" id="wbtTitle" /></h1>
<div id="graph">
<p>Graph to go here</p>
</div>
<p><strong>Notes: </strong></p>
<p><span><input type="textarea" id="wbtNote" /></span></p>
</div>
</article>
</section>
<button>Add New WBT Chart</button>
</body>
Here is the jQuery code I wrote:
$(document).ready(function() {
$("h1").keypress(function(e) {
//get
wbtTitle = $('#wbtTitle').val();
// Write text after enter
if (e.which == 13) {
$("h1").text(wbtTitle);
}
});
$("span").keypress(function(e) {
//get
wbtNote = $('#wbtNote').val();
// Write note after enter
if (e.which == 13) {
$("span").text(wbtNote);
}
});
//Insert new WBT on button click
$("button").each(function() {
$(this).click(function() {
var wbtSet = $( "article" ).html();
$(wbtSet).insertAfter('section');
});
});
});
What I want to do is set the title and some note text using input boxes which works using jQuery. I then want to add a copy of the html into another article when the button is pressed without copying the inputs previously made with the possibility of setting new values when the article is cloned. The process should repeat over and over again.
Here is an image to help explain:
I am quite new to jQuery, I think you need to use a loop to fix this, I read that a .each() can be used http://api.jquery.com/jQuery.each/ but not quite sure.
Any help will be appreciated. Thanks.
I think I got your answer.
I changed the html a bit, because you duplicated some id's with your approach, that's not good. id's have to be unique on a page. I simply changed them to classes.
<!DOCTYPE html>
<html>
<head>
<title>WBT Charts</title>
<link rel="stylesheet" type="text/css" href="wbt.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="wbt.js"></script>
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,500,700' rel='stylesheet' type='text/css'>
</head>
<body>
<section>
<article>
<div class="wbtBlock">
<p>Press enter to save amendments</p>
<h1>Title of wbt:<input type="text" class="wbtTitle" /></h1>
<div class="graph">
<p>Graph to go here</p>
</div>
<p><strong>Notes: </strong></p>
<p><span><input type="textarea" class="wbtNote" /></span></p>
</div>
</article>
</section>
<button>Add New WBT Chart</button>
</body>
And of course the jQuery. I got rid of your first two functions because they had no purpose in this context.
$(document).ready(function() {
//Insert new WBT on button click
$("button").on('click', function() {
var title = $(this).prev().find('.wbtTitle').val();
var note = $(this).prev().find('.wbtNote').val();
var wbtSet = $(this).prev("section").html();
$(this).prev().find('.wbtTitle').replaceWith(title);
$(this).prev().find('.wbtNote').replaceWith(note);
$(this).prev("section").after('<section>' + wbtSet + '</section>');
});
});
Here is a working fiddel
Fixing the answer given by hitokun_s
window.onload = function() {
// Save a copy of the element wbtSet element on pageload
var wbtSet = $("article").clone();
$("button").each(function() {
$(this).click(function() {
// Append a new one to the holder of the wbSets
$(wbtSet).appendTo($('section'));
});
});
}
I think this is what you want to do.
window.onload = function() {
$("button").each(function() {
$(this).click(function() {
var wbtSet = $("article:first-child").clone();
wbtSet.find("input").val("");
$(wbtSet).appendTo($('section'));
});
});
}

Categories