Cloning div and changing attributes - javascript

I performed various research but I din't find a solution for my problem. I created a drop down select with css to change color of background, but then when I try to clone it with Javascript, the new copy doesn't change attributes in selection so it keep the original color. Just try it, add some copy and try to change the colors.
I'm new here, i'm not very able to add code so here's to try:
http://jsfiddle.net/gabry501/FUyA3/
or github
https://github.com/gabry501/Test-Color/blob/master/test.html
HEAD
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function cloning() {
var container = document.getElementById('fine');
var clone = document.getElementById('contenitore').cloneNode(true);
container.appendChild (clone);
}
STYLE
select option,
select {
background-color:white;
width:200px;
height:200px;
}
select option[value="1"],
select.o1
{
background-color:blue;
}
select option[value="2"],
select.o2
{
background-color:red;
}
select option[value="3"],
select.o3
{
background-color:orange;
}
BODY
<div style="width:1100px;
height:250px;" id="contenitore">
SCRIPT
<script>$('select[id$=-status][id^=id_item-]').children().each(
function (){
if($(this).val() == 0){
$(this).css('backgroundColor','white');
}
if($(this).val() == 1){
$(this).css('backgroundColor','green');
}
if($(this).val() == 2){
$(this).css('backgroundColor','red');
}
if($(this).val() == 3){
$(this).css('backgroundColor','orange');
}
}
);</script>
<script>
$('select[id$=-status][id^=id_item-]').change(function (){
var color = $(this).find('option:selected').val();
$(this).removeClass('o1 o2 o3').addClass('o' + $(this).find('option:selected').val());
}).change();

It seems you are depending on a listener to modify the style. Listeners added using addEventListener are not included in a cloned element, you have to attach them seperately.
Note that listeners added inline, or using attachEvent are cloned.

cloneNode() copies only the data of the element in question. it does not copy over the event listeners. You need to do that manually..
Use the jQuery clone() method..
function cloning() {
var container = document.getElementById('fine');
var clone = $(document.getElementById('contenitore')).clone(true);
$(container).append(clone);
}
Check Fiddle
PS : Also you code looks really messy . You can scale it down..
UPDATE
I have made a few changes to the code .
1.) Removed the click event from HTML and added that to the script.
2.) Removed the ID's and replaced by a className as ID's in a document are supposed to
be Unique.
3.) Removed extra styles and replaced with a simple class Name.
4.) Better to have separate files for style and script than including it in HTML.
5.) If you want it to work , move the styles and the script to the corresponding tags I
have marked..
HTML
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style type="text/css">
// Add the Styles here
</style>
</head>
<body>
<div style="width:1100px; height:250px;" class="contenitore">
<select name="item-0-status">
<option value="" disabled="disabled" class="optionGroup">SELECT
COLOR</option>
<option value="1"> BLUE</option>
<option value="2"> RED </option>
<option value="3"> ORANGE</option>
</select>
</div> <!--Contenitore -->
<div id="fine"></div>
<br>
<div id="bottone">
<input id="btn" type="button" Value="ADD">
</div>
<script type="text/javascript">
// Script Comes Here
</script>
</body>
</html>
Javascript
$(function() {
$('select[name="item-0-status"]').change(function() {
$(this).removeClass('o1 o2 o3').addClass('o' + $(this).val());
}).change();
$('#btn').on('click', function() {
var container = document.getElementById('fine');
var clone = $(document.getElementsByClassName('contenitore')[0]).clone(true);
$(container).append(clone);
});
});​
Styles
#bottone
{
float:left;
text-align:left;
clear:left;
margin-top:20px;
}
select option,select
{
background-color:#FFF;
width:200px;
height:200px;
}
.o1
{
background-color:blue;
}
.o2
{
background-color:red;
}
.o3
{
background-color:orange;
}​
UPDATED FIDDLE

You have to use $('.el').live('change', fn) instead of $('.el').change(fn) because you're adding an element after the DOM is loaded.
See this jsfiddle: http://jsfiddle.net/FUyA3/1/

try deep cloning - i.e $(selector).clone(true)....then events will also be cloned

Related

How to change the colour of a div element when clicked?

I have a this html page, Whenever the element with class name FreeSeat is clicked I want to change the colour of that div element.Below is my html page
<html>
<head>
<title>
QuickBus
</title>
<link type="text/css" rel="stylesheet" href="Seat.css">
</head>
<body>
<div id="Bus">
<div class="Row">
<div class="FreeSeat" ></div>
<div class="FreeSeat" ></div>
<div class="ResSeat" ></div>
<div class="ResSeat" ></div>
<div class="ResSeat" ></div>
</div>
</div>
<body>
</html>
It will be very helpful if anyone can help me out with this .
Considering that you want to use pure JS and not any library, you'd have to manually add event listeners to your classes.
And it has been solved for a similar problem here
var freeclass = document.getElementsByClassName("FreeSeat");
var myFunction_Free = function() {
this.style.color = "blue";
}
for(var i=0;i<freeclass.length;i++){
freeclass[i].addEventListener('click', myFunction_Free, false);
}
But for your case, here's a working fiddle
JQuery is amazing for these sorts of things.
Say you have a div with id 'box1'
<div id='box1'></div>
Style it with css
#box1 {
width:100px;
height:100px;
background-color:white;
border:1px solid black;
}
Using JQuery, you can make this call:
$( "#box1" ).click(function() {
$('#box1').css('background-color', 'red');
});
And now whenever your div is clicked, the colour will change, you can customise this however much you like.
Here is a JSFiddle demo.
Also, since you didn't specify exactly what you want to change the colour of, in my example jquery, it is telling the browser that when a div with an id of box1is clicked, change the background-color of the div with an id of box1, you can change anything though.
If you have a <p> tag you can change that too when the div is clicked, hope this helped!
You can use the following method to change the background color of an element by class:
const free_seat = document.getElementsByClassName('FreeSeat');
free_seat[0].style.backgroundColor = '#ff0';
Each element can be referenced by its index:
free_seat[0] // first div
free_seat[1] // second div
Therefore, we can create a function that will be called whenever the click event is delivered to the target:
const change_color = () => {
this.style.backgroundColor = '#ff0';
};
for (let i = 0; i < free_seat.length; i++) {
free_seat[i].addEventListener('click', change_color);
}
Note: You can also use document.querySelectorAll('.FreeSeat') to obtain a NodeList of elements of a certain class.
You can use simply the css focus pseudo-class for this:
#foo:focus {
background-color:red;
}
<div id="foo" tabindex="1">hello world!</div>
Dont forget to set the tabindex.

Toggle class from dropdown menu

I try to toggle a class by selecting a option in the dropdown menu, i've tried using a alert() to check if it works but i cant seem to get it to work.
HTML:
<html>
<body>
<select id="dropdown">
<option value="1">Steinkjer</option>
<option value="2">Verdal</option>
</select>
</body>
</html>
Javascript:
$('#dropdown option:selected').click(function(){
var getText = $('#dropdown option').text();
alert($('.overlay-'+getText));
});
Please help me solve this issue.
$('#dropdown option:selected') is not a live object. Your code binds the click handler to the selected option on page load. You should either use event delegation or better listen to change event of the select element.
$('#dropdown').on('change', function() {
// Get text content of the selected option
var getText = $('option:selected', this).text();
// Get current value of the select element
// var getValue = this.value;
console.log(getText);
console.log($('.overlay-'+getText));
});
You need to:
Check document.ready is executed
Assign the change event
To bind some events to DOM elements, requires a document.ready, to
ensure the DOM element is sure created at the time you associate the
event.
A page can't be manipulated safely until the document is "ready.": https://learn.jquery.com/using-jquery-core/document-ready/
Check this snippet:
$(document).ready(function() {
$('#dropdown').change(function() {
var getText = $('#dropdown option:selected').html();
$("#test").removeClass();
$("#test").toggleClass("overlay-" + getText);
});
});
.overlay-Steinkjer {
background-color: red;
}
.overlay-Verdal {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<select id="dropdown">
<option value="1">Steinkjer</option>
<option value="2">Verdal</option>
</select>
<p id="test">test paragraph</p>
</body>
</html>

Javascript- creating element as a child of another element

Hello here's my simple code.I want to display image created in function add(src){} in element main_container.Why doesn't it work?
<head>
</head>
<body>
<style>
#main_container
{
width:1000px;
height:1000px;
position:absolute;
border-style:solid;
}
.jersey
{
width:100px;
height:150px;
position:absolute;
}
</style>
<script>
var dist=-110;
function add(src)
{
dist=dist+110;
var img=document.createElement("img");
img.src=src;
img.style.left=dist+"px";
img.className="jersey";
document.getElementById("main_container").appendChild(img);
}
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
</script>
<div id="main_container"></div>
</body>
</html>
Move the script tag below the element.
Change:
<script>...</script>
<div id="main_container"></div>
To:
<div id="main_container"></div>
<script>...</script>
The browser reads HTML from top to bottom.
beautifulcoder's suggested modification should work, and he is absolutely correct that this is happening because the main_container DOM element will not yet be loaded if it appears after the <script>, but ideally, you should hold off on making DOM manipulations until the document has loaded. You can do this by using the window.onload event:
<script>
function add(src) {
...
}
function initialize() {
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
}
window.onload = initialize;
</script>
<div id="main_container"></div>
or even better, use jQuery's ready event:
function initialize() {
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
}
$(document).ready(initialize);
// $(initialize); <- Shorthand version
Either of these approaches will free you from having to worry about where your script blocks are relative to your page elements.

Create clickable grid jQuery/Javascript

My goal is to create a clickable grid in jQuery/javascript that when a cell is clicked it will return the index value of the cell and then not allow for anymore clicking after the first click (I'm working on a board game so a click on the board would be a move and once you have moved you can't move until your next turn). However, currently I'm having issues simply getting my click event to work properly.
For now I'm just looking to make it so when I click on my grid it changes the color of the cell to red.
I looked at Creating a Clickable Grid in a Web Browser but I have very little experience with js so I was fairly confused by how the callback functions worked. Therefore I was attempting to use part of that example and jQuery which seems, at least to me, to be much more understandable when it comes to attaching events to things.
EDIT: Forgot to say what my issue was but its the fact that when I run all of the following code and click on the grid nothing happens.
grid.js:
$(document).ready(function()
{
grid();
});
$("#grid td").click(function()
{
alert("Clicked!");
$("#grid td").addClass("clicked");
});
function grid()
{
var grid = document.getElementById("grid");
for(var r = 0; r<18; r++)
{
var tr = grid.appendChild(document.createElement('tr'));
for(var c = 0; c<18; c++)
{
var cell = tr.appendChild(document.createElement('td'));
}
}
}
grid.css:
.grid { margin:1em auto; border-collapse:collapse }
.grid td {
cursor:pointer;
width:30px; height:30px;
border:1px dotted #ccc;
text-align:center;
font-family:sans-serif; font-size:16px
}
.grid td.clicked {
background-color:red;
}
test.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="grid.css" rel="stylesheet">
<script src="grid.js"></script>
</head>
<body>
<table class="grid" id="grid">
</table>
</body>
</html>
I would change the event handler. I built a little sample in jsfiddle that might help. If not, please let us know specifically what you are having trouble with.
http://jsfiddle.net/richbuff/gLF4W/
$("td").bind("click", function(){
alert( $(this).text() );
// change style here
$(this).addClass("clicked");
});
Edit: Please put the click handler inside the ready() handler like this:
$(document)ready({
grid();
$("td").bind("click", function(){
alert( $(this).text() );
// change style here
$(this).addClass("clicked");
});
The issue is that the table (#grid) does not exist when the handler is being defined. You could also try putting the handler after the table tag.

Selecting <li> item using jQuery after doubleclick

Here's what I'm trying to do:
I have an input field one can use to add entries to a todo list. I use JQuery to display a sorted list of entries after the user clicks 'Add'. I also made the list sortable (You can change the order by mouse drag using jQuery.) Now what I want to bold an individual list item when it is double-clicked. Somehow I'm not getting the jQuery to select the right item...
Here's my code.
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src='script.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<title>Tadum</title>
</head>
<body>
<h2>Tadum - The ToDo List</h2>
<h3>Enter New ToDos</h3>
<form id="addForm">
<input type="text" name="ToDoListItem"></input>
</form>
<div id="button">Add!</div>
<h3>Your ToDos</h3>
<ol class="todolist"></ol>
</body>
</html>
CSS:
.todolist li{
font-weight: normal;
}
.todolist {
font-family:garamond;
color:#cc0000;
}
Javascript
$(document).ready(function() {
$('#button').click(function(){
var toAdd = $('input[name=ToDoListItem]').val();
$('.todolist').append('<li class="item">'+toAdd+'</li>');
$('#addForm')[0].reset();
});
$('ol').sortable();
$('ol').css('cursor', 'pointer');
$('.todolist li').dblclick(function(){
$(this).css('font-weight', 'bold');
});
});
NOTE:
Somehow what works is if I replace the .list li in jQuery and in the CSS stylesheet with a simple ol. Then a doubleclick displays all items in the list (which is, of course, not what I want). But somehow I can't figure out how to only select the individual <li> that is doubleclicked with jQuery...
(I also tried a bunch of variations on this. For example, only use 'li' to select the doubleclicked item or use 'ol li', or '.item li'. None of them work.)
You need to bind the dblclick event handler to the newly added list items, like this:
$(document).on('dblclick', '.todolist li', function(){
$(this).css('font-weight', 'bold');
});
Please note that this doesn't toggle the style, but just makes them bold on double click. If you double click again it won't do anything.
Also if I may suggest some other changes to your JavaScript code: Your form can be normally submitted like any other form, for the purposes of this to do list anyways. I've also added a label to the HTML <form> for accessibility purposes.
$(document).ready(function() {
$('#addForm').submit(function(e){
e.preventDefault();
$('.todolist').append('<li class="item">' + $('#ToDoListItem').val() + '</li>');
$(this)[0].reset();
});
$('ol').sortable().css('cursor', 'pointer');
$(document).on('dblclick', '.todolist li', function() {
$(this).css('font-weight', 'bold');
});
});
HTML
<form id="addForm">
<label for='ToDoListItem'>Item:</label>
<input type="text" id="ToDoListItem" />
<button type='submit'>Add!</button>
</form>
You are adding the li items after the document was created. So you need to use "on" method so that you can trigger the click on the newly created items afterwards.
$(document).ready(function() {
$('#addForm').submit(function(e){
e.preventDefault();
var toAdd = $('#ToDoListItem').val();
$('.todolist').append('<li class="item">'+toAdd+'</li>');
$('#ToDoListItem').reset();
});
$('ol').sortable().css('cursor', 'pointer');
$(document).on('dblclick','li.item',function(){
$(this).css('font-weight', 'bold');
});
});

Categories