I am trying to change the alignment of textbox dynamically and it is not working. But if I give through on load of widget that is working fine.
code; HTML
<input type="text" id="text1" style="text-align:center;width:80px" value="abc">
<input type='button' id="btn" value="click">
JavaScript:
document.getElementById('btn').onclick = function(){
console.log(document.getElementById('text1').style.textAlign);
document.getElementById('text1').style['text-align'] = "left";
}
You can fix this bug by using the ::-ms-value pseudo element. You need to add some padding so it triggers a repaint. As it is the pseudo element rather than the actual element you are adding padding too, it looks like it doesn't change the actual width of the input. It also has the advantage of not being applied to non-IE browsers.
CSS:
.update::-ms-value {
padding-right: 1px;
}
JS:
document.getElementById('text1').className += "update";
http://jsfiddle.net/yHnLK/22/
Of course, you’d want to store the text1 element in a variable so you don't keep calling getElementById each time. Adding the text-align: left; via CSS would also be better, rather than adjusting the style object directly.
Try this code. Hope it help you with a good solution.
I set width to zero value then using timer to set width to the previous value to make it rendering again.
HTML:
<div>
<textarea name="text">WANDER LUST</textarea>
</div>
<div>
<button class="btn-text-align" data-rule="textAlign" data-value="left">Left</button>
<button class="btn-text-align" data-rule="textAlign" data-value="center">Center</button>
<button class="btn-text-align" data-rule="textAlign" data-value="right">Right</button>
</div>
Javascript:
(function($) {
$('.btn-text-align').on('click', function(){
$obj= $(this);
rule= $obj.attr('data-rule');
ruleValue= $obj.attr('data-value');
textElement= $(':input[name="text"]')[0];
textElement.style[rule]= ruleValue;
width= textElement.style['width'];
textElement.style['width']= '0px';
timerElement = setInterval(function () {
textElement.style['width']= width;
clearInterval(timerElement);
}, 10);
})
})(jQuery);
http://jsfiddle.net/zLwq140x/
Try this code, it works in IE:
Javascript:
document.getElementById('btn').onclick = function(){
console.log(document.getElementById('text1').style.textAlign);
document.getElementById('text1').style.textAlign = "left";
}
MDN CSS Properties Reference
Related
When trying to submit a form with missing required fields, my browser (Chrome), displays a message mentionning there is a field missing, and if it's out of my screen, it scrolls up to it.
My problem is that I have a 50px fixed header in my webpage, and as a result, the input field is hidden, and the message seems to come out of nowhere:
Instead of
Is there a way around this?
I tried both applying the 50px margin to <html> and to <body>
Cheers
EDIT
Here's a fiddle of the problem: http://jsfiddle.net/LL5S6/1/
I had the exact same problem and resolved it using jquery with this bit of code:
var delay = 0;
var offset = 150;
document.addEventListener('invalid', function(e){
$(e.target).addClass("invalid");
$('html, body').animate({scrollTop: $($(".invalid")[0]).offset().top - offset }, delay);
}, true);
document.addEventListener('change', function(e){
$(e.target).removeClass("invalid")
}, true);
Offset should be the height of your header and delay is how long you want it to take to scroll to the element.
The only way I found is adding an 'override' to the invalid handler.
To implement this for every input in your form you can do something like this.
var elements = document.querySelectorAll('input,select,textarea');
var invalidListener = function(){ this.scrollIntoView(false); };
for(var i = elements.length; i--;)
elements[i].addEventListener('invalid', invalidListener);
This requires HTML5 and this is tested on IE11, Chrome and Firefox.
Credits to #HenryW for finding that scrollIntoView works like expected.
Note that the false parameter for scrollIntoView aligns the input with the bottom, so if you have a large form it may be aligned with the bottom of the page.
jsfiddle
In modern browsers there is a new CSS property for that use case:
html {
scroll-padding-top: 50px;
}
Your JSFiddle updated: http://jsfiddle.net/5o10ydbk/
Browser Support for scroll-padding: https://caniuse.com/#search=scroll-padding
When there are several invalid inputs in the form, you only want to scroll to the first of them:
var form = $('#your-form')
var navbar = $('#your-fixed-navbar')
// listen for `invalid` events on all form inputs
form.find(':input').on('invalid', function (event) {
var input = $(this)
// the first invalid element in the form
var first = form.find(':invalid').first()
// only handle if this is the first invalid input
if (input[0] === first[0]) {
// height of the nav bar plus some padding
var navbarHeight = navbar.height() + 50
// the position to scroll to (accounting for the navbar)
var elementOffset = input.offset().top - navbarHeight
// the current scroll position (accounting for the navbar)
var pageOffset = window.pageYOffset - navbarHeight
// don't scroll if the element is already in view
if (elementOffset > pageOffset && elementOffset < pageOffset + window.innerHeight) {
return true
}
// note: avoid using animate, as it prevents the validation message displaying correctly
$('html,body').scrollTop(elementOffset)
}
})
JSFiddle
ok, i did a dirty test with a code snippet i found here on SO
As it is a code from someone else, i just alter it to scroll to the element that had a missing input requirement.
I do not want any credit for it, and it maybe is not even what you have in mind, you or someone else could use it as a reference.
The goal was to get the id of the forgotten/wrong input element:
var myelement = input.id;
var el = document.getElementById(myelement);
el.scrollIntoView(false);
Please keep in mind that this fiddle only works for your posted fiddle above, it not handles multiple forgotten or wrong input fields.I only wanted to show an alternative.
----->jSFiddle
I tried to use the way of T.J. Moats, but it did not work as needed, because I often came back to the field, which was incorrect first.
So, I made it:
var navhei = $('header').height();
var navheix = navhei + 30;
document.addEventListener('invalid', function(e){
$(e.target).addClass("invalid");
$('html, body').animate({scrollTop: $($(".invalid")[0]).offset().top - navheix }, 0);
setTimeout(function() {
$('.invalid').removeClass('invalid');
},0300);
}, true);
body {
margin: 0;
margin-top: 50px;
text-align: center;
}
header {
position: fixed;
width: 100%;
height: 50px;
background-color: #CCCCCC;
text-align:center;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<header>This is the header</header>
<div>
<form action="">
<br>
<input id="text" type="text" required="required" /><br><br>
<input id="text" type="text" required="required" /><br><br><br><br>
<input id="text" type="text" required="required" /><br><br>
<input id="text" type="text" required="required" /><br><br><br><br>
<input id="text" type="text" required="required" /><br><br><br><br><br><br>
<input id="text" type="text" required="required" /><br><br>
<p>Click send (at the bottom of the page), without filling the input field.</p><br><br><br><br><br><br>
<input id="text" type="text" required="required" /><br><br>
<input type="submit" id="btnSubmit" />
</form>
</div>
I hope it will be helpfull for people :)
You can use oninvalid event attribute of HTML5 and in your script's tag write a function for redirecting it.
Here is the example:
<input type="text" required oninvalid="scroll_to_validator(this)">
<script>
function scroll_to_validator(input)
{
input.focus();
}
</script>
And on clicking on your submit button it will scroll to the invalid field.
For radio button please add only on one radio with same nameHere is the example (jsfiddle)
Two solutions:
One: apply padding to the body -->
body {
padding-top:50px;
}
Two : apply margin to the main container -->
#content {
margin-top:50px;
}
Here's an EASY and FAST way.
$('input').on('invalid', function(e) {
setTimeout(function(){
$('html, body').animate({scrollTop: document.documentElement.scrollTop - 150 }, 0);
}, 0);
});
I've been trying to figure out how I can change the background color of a form element when it is clicked on.
Heres the code:
<form id="form">
<input type="text" placeholder="text"/>
<input type="password" placeholder="more text" />
</form>
<script>
</script>
I'm trying to make it so the form element where it says "text" turns green when clicked, and the form element where it says "more text" turns red when clicked.
I've tried this, which didn't work:
<script>
let form = document.queryselector('input type="text"');
form.addEventListener('click', () => {
form.style.backgroundColor = 'green'
});
</script>
I'm very new to coding, so any help is very much appreciated! Thanks!
you should write ('input[type="text"]');
<script>
let form = document.querySelector('input[type="text"]');
form.addEventListener("click", () => {
form.style.backgroundColor = "green";
});
</script>
If you just want the input background to change color while it's focused. You can achieve this by using CSS selectors. No need for JS
input[type=text]:focus {
background-color: red;
}
Or if you want the form background to change
form:focus-within {
background-color:red;
}
The issue is with this line:
let form = document.queryselector('input type="text"');
First of all - the querySelector() method is camel cased - note the capital S. Secondly, your selector is not quite correct - you're looking for: input[type="text"]:
let form = document.querySelector('input[type="text"]');
form.addEventListener('click', () => {
form.style.backgroundColor = 'green'
});
<form id="form">
<input type="text" placeholder="text"/>
<input type="password" placeholder="more text" />
</form>
Notice though that this doesn't change the background colour back once you focus out - you might be better off adding event listeners for the focusout, focusin and maybe blur events - but better still, you can use CSS:
form input[type="text"]:focus {
background-color: green;
}
I would recommend add and Id or a css class into your input tag then you can use querySelector --> https://www.w3schools.com/jsref/met_document_queryselector.asp
I am attempting to implement a "Light/Dark Mode" feature to a real time text editor, however due to the use of srcdoc the iframe refreshes and removes any CSS applied to it via JQuery. I would like to be able to keep the CSS within the iframe's contents.
I've attempted to make use of .css() to the contents of my frame, which works, but since I'm refreshing the frame on each keyUp event, the CSS is refreshed and no longer applied.
Appending the stylesheet also seems to result in it being "cleared" when refreshing.
How can I get the CSS to stay applied to the frame?
HTML
<div>
<textarea id="text-input" onkeyup="refresh()" placeholder="Enter your code here.."></textarea>
</div>
<div>
<iframe id="output-display"></iframe>
</div>
Javascript
function refresh(){
var input = document.getElementById('text-input').value;
document.getElementById('output-display').srcdoc = input;
}
$(document).ready(function(){
$('#output-display').contents().find('body').css('color', 'white');
});
EDIT:
The aim of this is to be a Real Time Editor, allowing a user to enter some code on the left (text area) and the result to be displayed on the right (iframe)
Ok so I think you don't actually have to use an iframe to accomplish what you are going for here. You could just use a regular html element and set the content at every keypress. Please see the code snippet below for reference:
var isDark = false;
function toggleTheme() {
if(isDark) {
$('#output-display').css({'background-color': 'black', 'color': 'white'});
isDark = false;
} else {
$('#output-display').css({'background-color': 'white', 'color': 'black'});
isDark = true;
}
}
function refresh() {
var inputValue = document.getElementById('text-input').value;
var parsedHtml = $.parseHTML(inputValue, document, true);
$('#output-display').html($(parsedHtml));
}
toggleTheme();
refresh();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="button" onclick="toggleTheme()" value="Toggle Theme" />
<br>
<textarea id="text-input" onkeyup="refresh()" placeholder="Enter your code here.."></textarea>
</div>
<div>
<div style="border: 1px solid black; width: 500px; height: 300px" id="output-display" disabled></div>
</div>
EDIT: added a theme toggle to illustrate further how you could use this.
EDIT2: added .parseHTML so you can add html to the input and render it
You can see in the picture of the two text input boxes (Firefox 52)
That the top one is the default appearance and the lower one has
changed after:
document.getElementById("answerBox").style.background = "white";
Do I have to recreate the element in order to get the default appearance back
or there an easier way?
Thanks for any help,
Gerard
I'm not sure to fully understand your question, but to restore a default appearance you can do something like this :
var btn = document.getElementById('btn');
var input = document.getElementById('input');
btn.addEventListener('click', function() {
input.classList.toggle('border');
});
input.border {
border: 1px solid red;
}
<label>Your answer</label>
<input id="input" type="text" />
<button id="btn">Click me</button>
The "classList.toggle('border')" add the border class to the input classList if not exists, and delete it if already exists.
How can I trigger an event when a div changes its height or any css attribute?
I have a div with id = mainContent. I want jquery to automatically trigger an event when it changes its height. I did something like this:
$("#mainContent").change('height', function() {
$("#separator").css('height', $("#mainContent").height());
});
I know its wrong.
Here's my whole code (I pasted all of it because I can't get into jsfiddle for some reason I don't know):
$(document).ready(function() {
$("#separator").css('height', $("body").height());
});
$(function() {
$("#btnSample1").click(function() {
$("#mainContent").css('height', '400px');
$("#mainContent").css('width', '600px');
$("#mainContent").css('background-color', '#F0F0F0');
});
$("#btnSample2").click(function() {
$("#mainContent").css('height', '1600px');
$("#mainContent").css('width', '700px');
$("#mainContent").css('background-color', '#F0F0F0');
});
$("#mainContent").change('height', function() {
$("#separator").css('height', $("#mainContent").height());
});
});
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#separator {
border-right: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width: 100%;">
<tr>
<td valign="top" style="width: 19%;">
<table id="mainMenu">
<tr><td><input id="btnSample1" type="button" value="Sample 1" /></td></tr>
<tr><td><input id="btnSample2" type="button" value="Sample 2" /></td></tr>
</table>
</td>
<td valign="top" style="width: 1%;" >
<div id="separator"></div>
</td>
<td valign="top" style="width: 80%;">
<div id="mainContent"></div>
</td>
</tr>
</table>
I am trying to adjust the height of the div id=separator based on the height of mainContent whenever the height of mainContent changes.
PS: In this case I know I can use the button event to do this but I want the div to trigger the event when the height is changed.
First, There is no such css-changes event out of the box, but you can create one by your own, as onchange is for :input elements only. not for css changes.
There are two ways to track css changes.
Examine the DOM element for css changes every x time(500 milliseconds in the example).
Trigger an event when you change the element css.
Use the DOMAttrModified mutation event. But it's deprecated, so I'll skip on it.
First way:
var $element = $("#elementId");
var lastHeight = $("#elementId").css('height');
function checkForChanges()
{
if ($element.css('height') != lastHeight)
{
alert('xxx');
lastHeight = $element.css('height');
}
setTimeout(checkForChanges, 500);
}
Second way:
$('#mainContent').bind('heightChange', function(){
alert('xxx');
});
$("#btnSample1").click(function() {
$("#mainContent").css('height', '400px');
$("#mainContent").trigger('heightChange'); //<====
...
});
If you control the css changes, the second option is a lot more elegant and efficient way of doing it.
Documentations:
bind: Description: Attach a handler to an event for the elements.
trigger: Description: Execute all handlers and behaviors attached to the matched elements for the given event type.
Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.
https://github.com/marcj/css-element-queries
It contains a ResizeSensor class you can use for that purpose.
new ResizeSensor(jQuery('#mainContent'), function(){
console.log('main content dimension changed');
});
Disclaimer: I wrote this library
For future sake I'll post this. If you do not need to support < IE11 then you should use MutationObserver.
Here is a link to the caniuse js MutationObserver
Simple usage with powerful results.
var observer = new MutationObserver(function (mutations) {
//your action here
});
//set up your configuration
//this will watch to see if you insert or remove any children
var config = { subtree: true, childList: true };
//start observing
observer.observe(elementTarget, config);
When you don't need to observe any longer just disconnect.
observer.disconnect();
Check out the MDN documentation for more information
Another simple example.
For this sample we can use 100x100 DIV-box:
<div id="box" style="width: 100px; height: 100px; border: solid 1px red;">
// Red box contents here...
</div>
And small jQuery trick:
<script type="text/javascript">
jQuery("#box").bind("resize", function() {
alert("Box was resized from 100x100 to 200x200");
});
jQuery("#box").width(200).height(200).trigger("resize");
</script>
Steps:
We created DIV block element for resizing operatios
Add simple JavaScript code with:
jQuery bind
jQuery resizer with trigger action "resize" - trigger is most important thing in my example
After resize you can check the browser alert information
That's all. ;-)
As far as regards the height or any other dimension parameter, you can use the ResizeObserver interface.
First, you get your HTML element:
const divElem = document.querySelector('#mainContent');
The element type is not restricted to DIVs, it can be anything.
Then, you create an instance of the ResizeObserver interface:
let myObserver = new ResizeObserver(entries => {
console.log("Height changed. New height: "+$("#mainContent").height());
});
Finally, you call the observe() method, which starts the specified element:
myObserver.observe(divElem);
Each time the element will be resized, the observe() method will be triggered.
Please note: the ResizeObserver interface does not work with Internet Explorer.
Other valuable answers are here:
How to detect DIV's dimension changed?