javascript highlight - javascript

i try to make the div color changed when click or focus on textbox so i do this js function but it change the textbox color not its div
<!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>
<title>test</title>
<style type="text/css">
/* This is the CSS class to use when no focus is on the input control */
.input_text
{
border:1px solid #c0c0c0;
padding:4px;
font-size:14px;
color:#000000;
background-color:#ffffff;
}
/* This is the CSS class to use when the control has focus */
.input_text:focus, input.input_text_focus
{
border-color:#646464;
background-color:#ffffc0;
}
</style>
<script type="text/javascript">
// creates a function to set the css class name of input controls when they
// receive or lose focus.
setAspnetTextFocus = function() {
// CSS class name to use when no focus is on the input control
var classBlur = 'input_text';
// CSS class name to use when the input control has focus
var classFocus = 'input_text_focus';
// get all of the input tags on the page
var inputElements = document.getElementsByTagName('input');
for (var i = 0; i < inputElements.length; i++) {
inputElements[i].onfocus = function() {
if (this.className == 'input_text') {
this.className += ' ' + classFocus;
}
}
// add the onblur event and set it to remove the on focused CSS class when it loses focus
inputElements[i].onblur = function() {
this.className = this.className.replace(new RegExp(' ' + classFocus + '\\b'), '');
}
}
}
// attach this event on load of the page
if (window.attachEvent) window.attachEvent('onload', setAspnetTextFocus);
</script>
</head>
<body>
<div class="input_text" >
<input type="text" id="TextBox1" class="input_text" />
</div>
</body>
</html>
any ideas?

To change the text select color you just need CSS. You wont be able to do it with JavaScript except with not so pretty hacks (you'd need to draw a rectangle on top/below the words on select...)
With CSS tho you just need to do (i believe):
#TextBox1::selection {
background: #ffb7b7; /* Safari */
}
#TextBox1::-moz-selection {
background: #ffb7b7; /* Firefox */
}
Source: http://css-tricks.com/overriding-the-default-text-selection-color-with-css/
Just a side note tho in case you care, this is NOT W3C validated CSS.

here is a jsfiddle using JQuery that will do what I think you are asking for: http://jsfiddle.net/pthurlow/GG6Te/
here it is in plain vanilla JS: http://jsfiddle.net/FSZZU/
EDIT code from jsfiddle:
html
<div class="input_text">
<input type="text" id="TextBox1" class="input_text" />
</div>
script
document.getElementById('TextBox1').onfocus = function() {
this.parentNode.className = 'input_text focus_text';
};
document.getElementById('TextBox1').onblur = function() {
this.parentNode.className = 'input_text';
};

Related

How to add   using appendChild in JavaScript?

Let's say I want to append a pattern like this in the DOM:
*
* *
* * *
* * * *
My JavaScript code looks like this:
function tri1()
{
let rows=document.getElementById("upperTri").value;
for(let i=1; i<=rows; i++)
{
for (let j=1; j<=i; j++)
{
document.getElementById("resTri1").appendChild(document.createTextNode(star));
}
document.getElementById("resTri1").appendChild(document.createElement("br"));
}
}
var star="*";
The thing is that I want to insert em space after each asterisk printed in the pattern, but HTML doesn't let one add more than one space unless it's an  , etc. But I couldn't find any way to appendChild() the emspace   in the DOM. It just prints the text   instead of the em space.
Any solution to this?
My HTML code:
<html>
<head>
<title>Pattern</title>
<script type="text/javascript" src="PB220322.js"></script>
</head>
<body>
<h1>JS Lab Session 22-03-22</h1>
<fieldset>
<legend><h2>Left Triangle</h2></legend>
<label for="upperTri">Enter the number of rows:</label>
<input type="number" name="upperTri" id="upperTri" onchange="tri1()">
<input type="submit" value="Enter" onsubmit="tri1()">
<div id="resTri1"></div>
</fieldset>
</body>
</html>
Append to the innerHTML of the parent element after appending the text node:
function tri1()
{
let rows=document.getElementById("upperTri").value;
for(let i=1; i<=rows; i++)
{
for (let j=1; j<=i; j++)
{
let elem = document.getElementById("resTri1")
elem.appendChild(document.createTextNode(star));
elem.innerHTML += " "
}
document.getElementById("resTri1").appendChild(document.createElement("br"));
}
}
var star="*";
<html>
<head>
<title>Pattern</title>
</head>
<body>
<h1>JS Lab Session 22-03-22</h1>
<fieldset>
<legend><h2>Left Triangle</h2></legend>
<label for="upperTri">Enter the number of rows:</label>
<input type="number" name="upperTri" id="upperTri" onchange="tri1()">
<input type="submit" value="Enter" onsubmit="tri1()">
<div id="resTri1"></div>
</fieldset>
</body>
</html>
Really quick:
Inline event handlers are garbage so in the example that onchange and onsubmit have been replaced with .addEventListener().
.createTextNode() is quite antiquated, albiet very stable, it renders text not HTML. .innerHTML and .textContent can destroy content if it isn't appended with a += operand. There is a method that isn't destructive and very versatile: .insertAdjacentHTML(). The Unicode characters you are trying to use can be in different formats:
// HTML Decimal & Hexidecimal
&ast; 
// CSS
\00002a\002003
// JavaScript
\u002a\u2003
&ast;  needs to be rendered as HTML so methods such as .insertAdjacentHTML() is ideal, but more often you'll see .innerHTML being used despite it's limitations.
The example below employs some useful interfaces from the HTML DOM API. There are extensive details commented in the example -- the following list are references pertaining to those comments:
HTMLFormElement
HTMLFormControlsCollection
HTMLFormElement Submit Event
Event.preventDefault()
Events
Event Delegation
Note: in the example the "stars" are just a fancier asterisk ❉.
// Event handler passes the Event Object
function tri(e) {
/*
Stop the default behavior of form#UI✺ during a "submit" event.
*/
e.preventDefault();
// Create a HTMLFormControlsCollection🞲 (>this< is form#UI)
const IO = this.elements;
/*
The value of input#rQty coerced into a real number
(prefixed with a plus '+' will coerce a string into number)
*/
const rows = +IO.rQty.value;
// ❉ and emspace in HTML decimal format;
const star = '❉ ';
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= i; j++) {
/*
iAHTML() renders htmlString into real HTML without destroying
content (unlike .innerHTML)
*/
IO.box.insertAdjacentHTML('beforeEnd', star);
}
IO.box.insertAdjacentHTML('beforeEnd', '<br>');
}
}
/*
Bind form#UI to the "submit" event.
When "submit" event fires, the event handler tri(e) will be invoked.
Note the terse syntax of the DOM Object:
document.forms.UI
this is from the HTMLFormElement interface.
*/
document.forms.UI.addEventListener('submit', tri);
/*
✺ form#UI is also >this< within the event handler because it is registered
to the "submit" event.
*/
/*
🞲 HTMLFormControlsCollection is part of the HTMLFormElement interface. It
is an array-like object consisting of all form controls under form#UI. Form
controls are:
<button>, <fieldset>, <input>, <object>, <output>, <select>, <textarea>
form controls may be referrenced by id or by name.
*/
html {
font: 2ch/1.15 'Segoe UI';
}
header {
margin-bottom: -12px;
}
h1 {
margin-bottom: 0;
}
fieldset {
min-width: max-content;
}
legend {
margin-bottom: -12px;
}
label,
input {
display: inline-block;
font: inherit;
margin-bottom: 4px;
}
#rQty {
width: 5ch;
text-align: right;
}
.box {
font-family: Consolas;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>JS Lab Session 22-03-22</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
/* Any CSS here has second highest priority */
</style>
</head>
<body>
<form id='UI'>
<header>
<h1>JS Lab</h1>
<p>Session 22-03-22</p>
</header>
<fieldset>
<legend>
<h2>Left Triangle</h2>
</legend>
<label for="rQty">Enter the number of rows: </label>
<input id="rQty" type="number" min='3' max='100' value='3'>
<input type="submit" value="Enter">
<fieldset name="box" class='box'></fieldset>
</fieldset>
</form>
<script>
/*
JavaScript can go here.
Place all external script tags directly above/before this
script tag.
*/
</script>
</body>
</html>

Onclick event is not working on first click

When the page loads I need to click the button twice to trigger the onclick() function. After doing so, everything works as expected.
As I am new to this web development field I would highly appreciate the detailed explanation.
Thank you in advance.
var hamburger = function() {
var menu = document.getElementById('menuBarSlide');
if (menu.style.right == "-300px") {
menu.style.right = "0px";
} else {
menu.style.right = "-300px";
}
}
<div class="navMenuItem hamburger" onclick="hamburger()">
<span class="ham-icon"></span>
<span class="ham-icon"></span>
<span class="ham-icon"></span>
</div>
I suppose that menuBarSlide is the id of a div, if so this should work for you.
I've added some styling to highlight the div, and a console.log() to be sure that the code executes.
Edit: Maybe the problem is that you expect the element to have a value in the right property but it is different, so logging the style can be helpful.
Edit 2: The problem is in the initial value (that is why your first click is not working, so with this variation menu.style.right = menu.style.right || "-100px"; that problem is solved. That line of code assigns -100px if the value comes null. Additionally, the program logs the value before and after the conditional assignment.
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<title>menuBarSlide</title>
<style>
#menuBarSlide { /*To highligth your div*/
position: absolute;
background-color: grey;
color: red;
}
</style>
</head>
<body>
<div class="navMenuItem hamburger" onclick="hamburger()">
<span class="ham-icon">Item1</span>
<span class="ham-icon">Item2</span>
<span class="ham-icon">Item3</span>
</div>
<div id="menuBarSlide">
<h1>menuBarSlide</h1>
</div>
<script>
var hamburger = function() {
var menu = document.getElementById('menuBarSlide');
console.log("before assing: " + menu.style.right); // To check the current style of the element
menu.style.right = menu.style.right || "-100px"; // Assign -100px if is null, otherwise keep the same value
console.log("after assing: " + menu.style.right); // To check the style after the asigment
if (menu.style.right == "-100px") {
menu.style.right = "30px";
}
else {
menu.style.right = "-100px";
}
}
</script>
<body>
<html>

Copying stored text in a table and then display it back into a textarea

I need your help,
How can I go about copying text (with the line breaks included) from my table and put it back into the textarea “newtext”
My existing coding doesn't seem to be working.
<html>
<head>
<style type="text/css">
.box { width: 400px; height: 50px; }
</style>
<script type="text/javascript">
function ta() {
taValue = document.getElementById("ta").value
taValue = taValue.replace(/\n/g, '<br/>')
document.getElementById("tatext").innerHTML = taValue
}
function text2area() {
document.getElementById("newtext").innerHTML = document.getElementById("tatext").innerHTML
}
</script>
</head>
<textarea class="box" id="ta" onkeyup="ta()"></textarea>
<table id="tatable"><tr><td><div id="tatext"></div></td></tr></table>
<br>
<input type="button" onclick="text2area()" value="move text">
<br><br>
<textarea class="box" id="newtext"></textarea>
</html>
Instead of using the function innerHTML, grab the value of the text area you want to capture, and set the value of the new text area to this. You are already using value for the variable taValue. Also, it's better practice to use addEventListener for your clicks and keyups.
function ta() {
taValue = document.getElementById("ta").value
taValue = taValue.replace(/\n/g, '<br/>')
document.getElementById("tatext").value = taValue;
}
function text2area() {
taValue = document.getElementById("ta").value;
document.getElementById("newtext").value = taValue;
}
document.getElementById("ta").addEventListener ("onkeyup", ta, false);
document.getElementById("move-text").addEventListener ("click", text2area, false);
JSFiddle: http://jsfiddle.net/tMJ84/1/
textarea does not have an innerHTML. Notice how you grabbed the value? Set it the same way! It is like this because it is a form element.
document.getElementById("tatext").value = taValue; //semi-colons are just good practice
and here:
document.getElementById("newtext").value = document.getElementById("tatext").value;

disable href after 1 click on html?

I want the href to be disabled after 1 click, can it be done using javascript or jquery?
Please help.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns ="http://www.w3.org 1999 xhtml" xml :lang="en">
<head>
<style>
a:link{
color:#1DAAA1;
}
a:visited{
color:green;
}
a:hover{
background: #ff0000;
color: #FFF;
}
</style>
</head>
<body>
<table width="500" align="center" border="5px solid">
<tr align="center" >
<td> Google </td>
<td> Yahoo </td>
<td> Bing </td>
<td> Wikipedia </td>
<td> Facebook </td>
</tr>
</table>
</body>
</html>
Pure javascript solution:
<script>
function clickAndDisable(link) {
// disable subsequent clicks
link.onclick = function(event) {
event.preventDefault();
}
}
</script>
Click here
This is simpler approach using jQuery that prevents links double clicking: no onclick attributes, id isn't required, no href removing.
$("a").click(function (event) {
if ($(this).hasClass("disabled")) {
event.preventDefault();
}
$(this).addClass("disabled");
});
Tip: you can use any selector (like button, input[type='submit'], etc.) and it will work.
just try this....
a:visited {
color:green;
pointer-events: none;
cursor: default;
}
Pure JavaScript solution to allow user to follow the URL only once:
<a id="elementId"
href="www.example.com"
onclick="setTimeout(function(){document.getElementById('elementId').removeAttribute('href');}, 1);"
>Clik and forget</a>
Once clicked, this will remove the href attribute (with 1 ms wait to allow the original action to start) making the link silent. Similar as suggested by Dineshkani, but the original answer caused action to not to start at all on some browsers.
this time i tried it with Javascript... hope it will help u:) just call the below function in "onclick()" of the required href tags...
​function check(link) {
if (link.className != "visited") {
//alert("new");
link.className = "visited";
return true;
}
//alert("old");
return false;
}​​
like ​link here​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
and see demo here
You can do with jquery
<a href='http://somepage.com' id='get' onlick='$("#"+this.id).attr("href","")'>Something to be go </a>
Or with the javascript
<a href='http://somepage.com' id='get' onlick='document.getElementById(this.id).removeAttribute("href");'>Something to be go </a>
Based on Ayyappan Sekar's answer, I have just done something very similar using jQuery:
$('#yourId').click(function (e) {
if(!$(this).hasClass('visited'))
{
$(this).addClass('visited')
return true;
}
else
{
$(this).removeAttr("href"); // optional
// some other code here
return false;
}
});
duplicate the same div in html and css, the duplicated one must be below the original one using: z-index=-1 or/and position:absolute.
make the original div onclick="HideMe(this)"
JS:
<script type="text/javascript">
function HideMe(element){
element.style.display='none';
}
</script>
it might be not the best way, but 100% goal achievable.
I want to leave here an example that works with Knockout.js that I used with IFrame, but as IFrame doesnt work with local files, I made this example with divs.
When you click the link, the function is called, as you can see with the alert()commented inside, but when you dial something in the input dialog and click again the link, the div is not updated by the Knockout.js, only if you click the other link that calls the same function but with diferent parameter.
<html>
<head>
<script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
</head>
<body>
<div>
Page 2
</div>
<div>
Page 3
</div>
<div data-bind="bindHTML: dados"></div>
<script type="text/javascript">
function myPage2(nPage) {
var cPage = '<div>Pagina 2</div>';
if (nPage == 3) { cPage = '<div>Pagina 3</div>' }
cPage += '<input type="text" id="fname" name="fname">';
//alert('clicked!');
return cPage
}
var viewModel = {
dados : ko.observable()
}
ko.bindingHandlers.bindHTML = {
init: function () {
// Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
return { 'controlsDescendantBindings': true };
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// setHtml will unwrap the value if needed
ko.utils.setHtml(element, valueAccessor());
var elementsToAdd = element.children;
for (var i = 0; i < elementsToAdd.length; i++) {
ko.cleanNode(elementsToAdd[i]); //Clean node from Knockout bindings
ko.applyBindings(bindingContext, elementsToAdd[i]);
}
}
};
ko.applyBindings(viewModel);
viewModel.dados(myPage2(2));
function fAlter(nPage) {
viewModel.dados(myPage2(nPage));
}
</script>
</body>
</html>
jQuery solution:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns ="http://www.w3.org 1999 xhtml" xml :lang="en">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function check(link) {
$(link).replaceWith($(link).text());
}
</script>
<style>
a:link{
color:#1DAAA1;
}
a:visited{
color:green;
}
a:hover{
background: #ff0000;
color: #FFF;
}
</style>
</head>
<body>
<table width="500" align="center" border="5px solid">
<tr align="center" >
<td> Google </td>
<td> Yahoo </td>
<td> Bing </td>
<td> Wikipedia </td>
</tr>
</table>
</body>
</html>

Cloning div and changing attributes

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

Categories