Changing HTML id via JS - javascript

I hava a script that consist of "hello world" and the "hello" and "world" are in two different CSS styles.
I would like to click onto either of them and they would swap their styles. Example is I click on "hello" and it would swap style with "world". Below is my codes.
I couldn't get it to swap. How should I correct it ?
<html>
<head>
<style>
#today{
font-weight: bold;
color: red;
}
#normal{
font-weight: normal;
color: green;
}
</style>
<script>
old="old";
function set(in){
var e = document.getElementsByName(old);
for(ii=0;ii<e.length; ii++)
{
var obj = document.getElementsByName(old).item(ii);
obj.id="normal";
}
old=in;
var e = document.getElementsByName(old);
for(ii=0;ii<e.length; ii++)
{
var obj = document.getElementsByName(old).item(ii);
obj.id="today";
}
}
</script>
</head>
<body>
<table>
<tr>
<td id="normal" name="new" onclick="set('new')">Hello</td>
<td id="today" name="old" onclick="set('old')">World</td>
</tr>
</table>
</body>
</html>

At any time, only one element can be annotated with an ID. Therefore, you should use classes instead of IDs to annotate your elements. Also, make sure to include a doctype.
Live demo of the corrected code:
<!DOCTYPE html>
<html>
<head>
<style>
.today{
font-weight: bold;
color: red;
}
.normal{
font-weight: normal;
color: green;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
var els = document.querySelectorAll('.normal,.today');
for (var i = 0;i < els.length;i++) {
els[i].addEventListener('click', function () {
var els = document.querySelectorAll('.normal,.today');
for (var i = 0;i < els.length;i++) {
var currentClass = els[i].getAttribute('class');
var newClass = currentClass == 'today' ? 'normal' : 'today';
els[i].setAttribute('class', newClass);
}
}, false);
}
}, false);
</script>
</head>
<body>
<table>
<tr>
<td class="normal">Hello</td>
<td class="today">World</td>
</tr>
</table>
</body>
</html>
Of course, it's way easier to write with jQuery (demo):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script>
$(function() {
$('.normal,.today').click(function() {
$('.normal,.today').each(function(i, el) {
var $el = $(el);
if ($el.hasClass('today')) {
$el.removeClass('today');
$el.addClass('normal');
} else {
$el.removeClass('normal');
$el.addClass('today');
}
});
});
});
</script>

You have a few problems here. First, in your onclick handler, it has to be "javascript:set" instead of just "set". Second, you have a parameter named "in" which is a Javascript keyword. Change all references of it to "inv". If you do that, your code will sort-of work. Try it.
Beyond that, I suggest that you work in Firefox, and get the Firebug add-in, so that you can open the console. It will show you these kinds of errors.

Related

Need to enlarge image at click and then reduce it again by clicking again on external javascript file

This large image is defined in the index.html with a class="small" attribute so it shows as a thumbnail.
<img id="smart_thumbnail" class="small" src="https://image.jpg">
On a separate .js file need to create a function to bring it back to it's normal size and then back to thumbnail by clicking it again. NEED to use if/else. What I am trying to do is to switch between class="" and class="small"
So far I have this but it is not working:
document.addEventListener("DOMContentLoaded", function(event) {
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
if(thumbnailElement.className = "small";){thumbnailElement.className = "";}
else
{thumbnailElement.className = "small";}
});
});
Any suggestions? Thanks.
Here is something that I made work. It uses JS style properties to change it, not CSS classes. You could copy or reference it:
var imgEl = document.getElementById("Img");
var isBig = false;
imgEl.addEventListener("click", function() {
if (isBig) {
imgEl.style.width = "30px";
imgEl.style.height = "30px";
isBig = false;
} else {
imgEl.style.width = "100px";
imgEl.style.height = "100px";
isBig = true;
}
})
#Img {
border: 1px solid black;
background-color: red;
width: 30px;
height: 30px;
transition: 1s;
}
<div id="Img">
The CSS class switcher isn't working because '=' is not an equal operator, it is an assignment operator. use '==' or '===' for equal operators.
The code above will only run once when the website is initially loaded. To solve this problem, you will need to modify the code so that it is constantly listening for an event.
The code for it should look something similar to the following:
<!DOCTYPE html>
<html>
<head>
<title>Resizing a square with event listeners</title>
<style type="text/css">
.small {
width: 50px;
height: 50px;
}
.large {
width: 100px;
height: 100px;
}
#smart_thumbnail {
background-color: blue;
}
</style>
</head>
<body>
<div id="smart_thumbnail" class="large"></div>
<script>
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
if (this.className == "small") {this.className = "large";}
else {this.className = "small";}
});
</script>
</body>
</html>
I also modified the smart_thumbnail so that it has a large/normal size class as well as a small class.

How can I make multiple buttons to change a different div background color?

Take a look at what I am trying to make:
https://codepen.io/SomeRandomGuy0/pen/aWvGxO
I was able to make the color of the square change color using the button "Blue". What I want to do is make multiple buttons to change the color of the square to what it says in the button. For example if I clicked on a button that says "Green", the square will turn green and if I clicked on another button that says "Purple", it will turn purple.
I am getting introduced to DOM in JavaScript so sorry for such a basic question.
HTML:
<html>
<head>
<meta charset = "UTF-8" />
<title>DOM Practice</title>
</head>
<body>
<div id = 'square'></div>
<button onClick = changeColor() >Blue</button>
</body>
</html>
CSS:
#square{
width: 100px;
height: 100px;
background-color: red;
}
JavaScript:
function changeColor(){
var elem = document.getElementById( 'square' );
elem.style.backgroundColor = 'blue';
}
You can pass the color as parameter on calling function at button
check this code pen
https://codepen.io/anon/pen/BRoPJo
<button onClick = changeColor('Blue') >Blue</button>
<button onClick = changeColor('green') >green</button>
<button onClick = changeColor('yellow') >yellow</button>
JS
function changeColor(color){
var elem = document.getElementById( 'square' );
elem.style.backgroundColor =color;
}
The simplest approach could be to update changeColor() to take an argument of color.
So for example,
Javascript:
function changeColor(color){
var elem = document.getElementById( 'square' );
elem.style.backgroundColor = color;
}
Then in the HTML we could do:
<html>
<head>
<meta charset = "UTF-8" />
<title>DOM Practice</title>
</head>
<body>
<div id = 'square'></div>
<button onClick = changeColor('blue') >Blue</button>
<button onClick = changeColor('red') >Red</button>
</body>
</html>
This will allow us to generalize the changeColor() function, and make it more reusable for future applications!
Use an if/else statement in your function, I'm not going to do it for you, but the logic should be, if blue button is clicked, change to blue, if red button is clicked change to red and so on.
data-attributes are great for this: https://jsfiddle.net/sheriffderek/0hm9wnk7/ I also like to use rel to hook the js into the markup instead of classes to keep things really clear.
<div class='square' rel='box'></div>
<ul class='color-list' rel='box-colors'>
<li class='color' data-color='red'>red</li>
<li class='color' data-color='blue'>blue</li>
...
</ul>
...
.square {
width: 100px;
height: 100px;
background: lightgray;
}
.color-list .color {
cursor: pointer;
}
...
// $('selector/element') - 'queries'(looks for) for the object in the DOM / j-'query' get it?
// var $thing (with $sign is just a convention to remind you that it's a jQuery object / that comes with some jQuery specific stuff)
var $box = $('[rel="box"]'); // cache the element with rel='box' to a pointer(variable) for use later
var $boxColors = $('[rel="box-colors"]'); // same idea
var $colorTriggers = $boxColors.find('.color'); // same idea / see .find() method
$colorTriggers.on('click', function() {
// .on() is a method for attaching event handlers - in this case, 'click'
thisColor = $(this).data('color'); // get the clicked element's data-attr for data-color
$box.css('background', thisColor); // set the box css background to the color you just retrieved from the data-attr
});
EDIT -- this approach is simplest IMO
Codepen DEMO
HTML:
<html>
<head>
<meta charset = "UTF-8" />
<title>DOM Practice</title>
</head>
<body >
<div id='preview'></div>
<input id="colorpicker" type="color" />
</body>
</html>
JS:
document.addEventListener('DOMContentLoaded', e => {
const preview = document.getElementById('preview');
const picker = document.getElementById('colorpicker');
preview.style.backgroundColor = picker.value;
picker.addEventListener('input', e => {
preview.style.backgroundColor = e.currentTarget.value
})
})
ORIGINAL -- an excuse to play with css vars
Here's an approach:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const getRandomColor = () => colors[Math.floor(Math.random() * colors.length)]
const selectColor = (color) => document.body.style.setProperty('--current', color);
document.addEventListener('DOMContentLoaded', e => {
const preview = document.getElementById('square');
const changeColor = (e) => {
let color = getComputedStyle(e.currentTarget).getPropertyValue('--color-name');
selectColor(color);
let logStyles = `
color: black;
font-weight: bold;
background-color: ${color};
font-size: 18px;`;
console.log(`color changed to %c ${color} `, logStyles);
}
// 1. select purple for starting color
// 2. create buttons
// NOTE: I created the buttons programatically, but you could just as easily
//
// <button style="--color-name:red;">red</button>
// <button style="--color-name:orange;">orange</button>
// etc...
selectColor('rebeccapurple')
colors.forEach((color, i) => {
let button = document.createElement('button');
button.style.setProperty('--color-name', color);
button.onclick = changeColor;
button.textContent = color;
document.body.appendChild(button);
})
})
body {
--current: 'green';
}
#square{
background-color: var(--current);
width: 150px;
height: 150px;
margin-bottom: 15px;
}
button {
padding: 8px 16px;
background: white;
border: 1px solid #f3f3f3;
color: var(--color-name);
margin-right: 8px;
}
<html>
<head>
<meta charset = "UTF-8" />
<title>DOM Practice</title>
</head>
<body >
<div id = 'square'></div>
</body>
</html>

How to highlight a column in html table on click using js or jquery?

I am trying to implement a javascript which will highlight the column in an html table on click.As the below working example for row highlight i tried to use the same with table.columns but table.columns doesn't exist.Is there any was to highlight the column in html table using jquery?
Working code for highlighting row:
Table Highlight POC
<script>
function highlight() {
var table = document.getElementById('dataTable');
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function () {
if (!this.hilite) {
this.origColor = this.style.backgroundColor;
this.style.backgroundColor = '#BCD4EC';
this.hilite = true;
}
else {
this.style.backgroundColor = this.origColor;
this.hilite = false;
}
}
}
}
</script>
<style>
table {
border-spacing: 0px;
}
td {
border: 1px solid #bbb;
padding: 0.2em;
}
</style>
</head>
<body>
<table id="dataTable">
<tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
<tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
<tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
</table>
</body>
</html>
You can use the following code:
$('td').on('click', function() {
var $currentTable = $(this).closest('table');
var index = $(this).index();
$currentTable.find('td').removeClass('selected');
$currentTable.find('tr').each(function() {
$(this).find('td').eq(index).addClass('selected');
});
});
Just put this on your JS file and it will work on all available tables independently. In case you want to use it only on a specific table, just change the initial selector to $('#myTable td').
Also dont forget to add the .selected{ background-color: #ace; } class in yor css file.
Here is the working example.
Cheers!
Please try this:
$("#dataTable tr td").click(function() {
//Reset
$("#dataTable td").removeClass("highlight");
//Add highlight class to new column
var index = $(this).index();
$("#dataTable tr").each(function(i, tr) {
$(tr).find('td').eq(index).addClass("highlight");
});
});
.highlight {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="dataTable">
<tr><td>Data1</td><td>Data2</td></tr>
<tr><td>Data1</td><td>Data2</td></tr>
<tr><td>Data1</td><td>Data2</td></tr>
</table>
A fork Fisnik Tahiri solution to support also the tr selection (based on css or jquery if you preferir)
css:
.selected{ background-color: #ace; }
tr:hover{ background-color: #ace; }
Js:
$('td').on('mouseenter', function() {
var $currentTable = $(this).closest('table');
//var $row = $(this).closest('tr');
var index = $(this).index();
//clean
$currentTable.find('td').removeClass('selected');
//select row if you want use js
//$currentTable.find('tr').removeClass('selected');
//$row.addClass('selected');
//select column
$currentTable.find('tr').each(function() {
$(this).find('td').eq(index).addClass('selected');
});
});
working example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>onclick highlight</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$( ".table tr" ).click(function(){
$(".table tr" ).css("background-color","white");
$(this).css("background-color","green");
});
});
</script>
</head>
<body>
<table class="table">
<tr>
<td>Date1</td>
<td>Date2</td>
<td>Date3</td>
</tr>
<tr>
<td>Date1</td>
<td>Date2</td>
<td>Date3</td>
</tr>
<tr>
<td>Date1</td>
<td>Date2</td>
<td>Date3</td>
</tr>
</table>
</body>
</html>

How to make UI more responsive for other screen sizes?

I have an html page in which I have a textbox (Type your text) and TextArea list. I need to type into the textbox and then click Add button so that whatever is there in textbox goes to my TextArea list. I need to type in this below format in the textbox.
Name=Value
This textbox will be used by the user to quickly add Name Value pairs to the list which is just below that textbox. let's say if we type Hello=World in the above textbox and click add, then in the below list, it should show as
Hello=World
And if we again type ABC=PQR in the same textbox, then in the below list, it should show like this so that means it should keep adding new Name Value pair just below its original entry.
Hello=World
ABC=PQR
But if the syntax is incorrect like if it is not in Name=Value pair then it should not add anything to the list and instead show a pop up that wrong input format. Names and Values can contain only alpha-numeric characters. I also have three more buttons Sort by name, Sort by value and Delete button. Once I click either of these buttons, then it should sort entries in TextArea list using either name or value and delete entries as well. Now I have all above things working fine without any issues.
Here is my jsfiddle. I need to use plain HTML, CSS and Javascript, I don't want to use any library yet as I want to keep it simple as I am still learning. Now I am trying to see whether we can make UI more responsive like the UI should adjust based on what screen size is viewing it. For example, if viewed on a mobile phone (i.e. Android or iPhone), the page should automatically adjust to present the layout in a better way. This also applies to re-sizing the browser on desktop, and viewing the page on a tablet.
What are the changes I need to make in my CSS or HTML to make it more responsive? Any improvements I can make here? Since my UI is very simple so there should be some easy way or some improvements I can make here.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<style type="text/css">
.main{
background:white;
padding: 35px;
border-radius: 5px;
}
#my-text-box {
font-size: 18px;
height: 1.5em;
width: 585px;
}
#list{
width:585px;
height:300px;
font-size: 18px;
}
.form-section{
overflow:hidden;
width:700px;
}
.fleft{float:left}
.fright{float:left; padding-left:15px;}
.fright button{display:block; margin-bottom:10px;}
html, body {
height: 100%;
font-family: "Calibri";
font-size: 20px;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
background-color: #5C87B2;
}
</style>
<script language="javascript" type="text/javascript">
document.getElementById('add').onclick = addtext;
function addtext() {
var nameValue = document.getElementById('my-text-box').value;
if (/^([a-zA-Z0-9]+=[a-zA-Z0-9]+)$/.test(nameValue)){
var x = document.getElementById("list");
var option = document.createElement("option");
option.text = nameValue;
x.add(option);
}
else
alert('Incorrect Name Value pair format.');
}
document.getElementById('btnDelete').onclick = deleteText;
function deleteText(){
var myList = document.getElementById('list');
var i;
for (i = myList.length - 1; i>=0; i--) {
if (myList.options[i].selected) {
myList.remove(i);
}
}
}
document.getElementById('sortByValue').onclick = sortByValue;
function sortByValue(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function(a, b){
if(a != "" && b != ""){
return a.split('=')[1].localeCompare(b.split('=')[1])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
document.getElementById('sortByName').onclick = sortByName;
function sortByName(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function (a, b){
if(a != "" && b != ""){
return a.split('=')[0].localeCompare(b.split('=')[0])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
function clearList(list) {
while (list.options.length > 0) {
list.options[0] = null;
}
}
function fillList(myList, values){
for (var i=0;i<values.length;i++) {
var option = document.createElement("option");
option.text = values[i];
myList.options[i] = option;
}
}
</script>
</head>
<body>
<div class = 'main'>
<h3>Test</h3>
<label for="pair">Type your text</label></br>
<div class="form-section">
<div class="fleft">
<input type='text' id='my-text-box' value="Name=Value" />
</div>
<div class="fright">
<button type="button" id='add' onclick='addtext()'>Add</button>
</div>
</div>
<label for="pairs">Name/Value Pair List</label></br>
<div class="form-section">
<div class="fleft">
<select id="list" multiple></select>
</div>
<div class="fright">
<button type="button" id='sortByName' onclick='sortByName()'>Sort by name</button>
<button type="button" id='sortByValue' onclick='sortByValue()'>Sort by value</button>
<button type="button" id='btnDelete' onclick='deleteText()'>Delete</button>
<button type="button">Show XML</button>
</div>
</div>
</div>
</body>
</html>
W3 have a number of resources on responsive web design:
http://www.w3schools.com/html/html_responsive.asp
http://www.w3schools.com/css/css_responsive_intro.asp
Without using PHP to detect the browser/user agent, your responsive design will typically involve ensuring the site is more fluid and flowing, allowing for changing browser widths (as in the first example above) and/or by delivering differing stylesheets depending on the viewport size and media type in CSS (second example).

Show more/less text in a table automatically according to text length

I have a table with two columns, the second one sometimes contains big text so I want to show only the first 100 characters and put a show more link to display the remaining text. You can see here what Table I am working on http://jsfiddle.net/j11mj21x/.
For that I am using a code provided in this link (http://viralpatel.net/blogs/dynamically-shortened-text-show-more-link-jquery/), I put it in a file show_less_more.js :
(function($) {
$.fn.shorten = function (settings) {
var config = {
showChars: 100,
ellipsesText: "...",
moreText: "more",
lessText: "less"
};
if (settings) {
$.extend(config, settings);
}
$(document).off("click", '.morelink');
$(document).on({click: function () {
var $this = $(this);
if ($this.hasClass('less')) {
$this.removeClass('less');
$this.html(config.moreText);
} else {
$this.addClass('less');
$this.html(config.lessText);
}
$this.parent().prev().toggle();
$this.prev().toggle();
return false;
}
}, '.morelink');
return this.each(function () {
var $this = $(this);
if($this.hasClass("shortened")) return;
$this.addClass("shortened");
var content = $this.html();
if (content.length > config.showChars) {
var c = content.substr(0, config.showChars);
var h = content.substr(config.showChars, content.length - config.showChars);
var html = c + '<span class="moreellipses">' + config.ellipsesText + ' </span><span class="morecontent"><span>' + h + '</span> ' + config.moreText + '</span>';
$this.html(html);
$(".morecontent span").hide();
}
});
};
})(jQuery);
$(document).ready(function(){$(".descriptionText").shorten();});
I am using it like this:
<script src="show_less_more.js"></script>"
The HTML is like this for every row:
<tr>
<th>
course1
</th>
<td> <div class="descriptionText">Description of the course</div></td>
</tr>
I have also added the CSS for the more and less links:
a {
color: #0254EB
}
a:visited {
color: #0254EB
}
a.morelink {
text-decoration:none;
outline: none;
}
.morecontent span {
display: none;
}
When I do this in sfiddle it works pretty good as you can see here http://jsfiddle.net/j11mj21x/2/
However, I get nothing when rendering my table with python.
I think the problem is that I don't succeed to load my JS page into the html page, because when I click on it it give nothing.
Here is what is rendered in my html page:
....
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"><!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"><!-- Latest compiled and minified JavaScript --><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js">
</script><script src="showLessMore.js"></script>
....
Can anyone tell me what could be the problem behind this because I have the "show_less_more.js" in the same folder as the file generator which in python?
Thank you in advance !
Here's a simple example of doing this relying more on CSS.
$(function() {
$('a').click(function() {
$('div').removeClass('ellipsis');
});
});
div {
border: solid 1px orange;
width: 200px;
overflow: hidden;
}
.ellipsis {
white-space: nowrap;
text-overflow: ellipsis;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='ellipsis'>Some really really long text that just is way too long so we must use ellipses to shorten it until the user wants to see it all.</div>
<br>
<a href='#'>Show All</a>

Categories

Resources