How can I prevent browser from scrolling when focusing? Here's my code:
select {
width: 200px;
height: 55em;
overflow: auto;
}
<br><br><br><br><br><br><br><br><br>
<select multiple>
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
</select>
Try choosing an option or two.
UPDATED
As your requirement, I'd suggest you use position: fixed for the temporary body block (removed immediately with setTimeout)
With this solution, onfocus is good enough (no need to have onblur)
function blockScroller(event) {
const body = document.getElementsByTagName("body")[0]
body.classList.add("scroller-blocker")
setTimeout(() => {
body.classList.remove("scroller-blocker")
})
}
select {
width: 200px;
height: 55em;
overflow: auto;
}
.scroller-blocker {
position: fixed;
height: 100%;
}
<br><br><br><br><br><br><br><br><br>
<select multiple onfocus="blockScroller(event)">
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
</select>
OLD ANSWER
You can block the scroller with overflow: hidden on your element body
onfocus is triggered whenever an user focuses on a element
onblur is triggered whenever an user clicks outside of a focused element
Note that for mobile devices, you need to remove touchmove event for completely blocking screen moving
const touchMoveEvent = function(e) {
e.preventDefault()
}
function blockScroller() {
const body = document.getElementsByTagName("body")[0]
body.classList.add("scroller-blocker")
//avoid touch move event on mobile
body.addEventListener('touchmove', touchMoveEvent)
}
function unblockScroller() {
const body = document.getElementsByTagName("body")[0]
body.classList.remove("scroller-blocker")
//put the default behaviour of touch move event back
body.removeEventListener('touchmove', touchMoveEvent)
}
select {
width: 200px;
height: 55em;
overflow: auto;
}
.scroller-blocker {
height: 100%;
overflow: hidden;
}
<br><br><br><br><br><br><br><br><br>
<select multiple onfocus="blockScroller()" onblur="unblockScroller()">
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
</select>
Related
I am trying to add a placeholder image in the paragraph tag. The users select an option and the photo is replaced by the one chosen. I have tried to add a photo as a valued on the first option but didn't work. Any ideas please?
select { outline: none; width: 100%; padding: 10px 0; text-align: center;}
<select onchange="document.getElementById('preview2').src = this.value">
<option selected="selected" disabled="disabled">Select a finish</option>
<option value="/images/image1.jpeg">Chrome</option>
<option value="/images/image2.jpeg">Satin Chrome</option>
<option value="/images/image3.jpeg">Black</option>
<option value="/images/image5.jpeg" ">Brushed Brass</option>
<option value="/images/image6.jpeg "">Brushed Nickel</option>
<option value="/images/image7.jpeg" ">Powdercoated Gun Metal</option>
<option value="/images/image8.jpeg "">Gun Metal</option>
<option value="/images/image9.jpeg" ">Antique Brass</option>
<option value="/images/image10.jpeg "">Black Chrome</option>
</select><br />
<p><img id="preview2" alt="" /></p>
Just trigger the change and have the default on the first option:
window.addEventListener("DOMContentLoaded", () => { // when the page haas loaded
const sel = document.getElementById("imgSel");
const img = document.getElementById('preview2');
const changeImg = () => { // called when image needs to be changed
img.src = sel.value;
img.title = sel.value;
console.log(img.src); // for debugging
};
sel.addEventListener("change", changeImg); // better than inline event handler
changeImg(); // initialise
})
#imgSel {
outline: none;
width: 100%;
padding: 10px 0;
text-align: center;
}
img {
height: 100px;
width: 100px;
border: 1px solid black;
}
<select id="imgSel">
<option selected="selected" disabled="disabled" value="/images/default.jpg">Select a finish</option>
<option value="/images/image1.jpeg">Chrome</option>
<option value="/images/image2.jpeg">Satin Chrome</option>
<option value="/images/image3.jpeg">Black</option>
<option value="/images/image5.jpeg">Brushed Brass</option>
<option value="/images/image6.jpeg">Brushed Nickel</option>
<option value="/images/image7.jpeg">Powdercoated Gun Metal</option>
<option value="/images/image8.jpeg">Gun Metal</option>
<option value="/images/image9.jpeg">Antique Brass</option>
<option value="/images/image10.jpeg">Black Chrome</option>
</select><br />
<p><img id="preview2" alt="" /></p>
I created a div which contains my counter that displays the "(n) option(s) selected." I want to locally store my div into html so that when I refresh my page it remains active. I am new to local storage, but understand it works with key value pairs.
I have created two variables:
var get_count = document.getElementsByClassName("counter");
var save_count = localStorage.getItem("counter");
My first variable returns an HTMLCollection[] and my second variable is returned as undefined. I am confused how to handle my key value pairs in my HTMLCollection[]. How can I locally store my div container that displays the total number of options selected?
$(document).ready(() => {
$.fn.select2.amd.require([
'select2/utils',
'select2/dropdown',
'select2/dropdown/attachBody'
], function (Utils, Dropdown, AttachBody) {
/* gets item */
var previousSelectionCount = window.localStorage.getItem('selectCount');
console.log('*****', previousSelectionCount);
function SelectAll() { }
SelectAll.prototype.render = function (decorated) {
var $rendered = decorated.call(this);
var self = this;
//define the buttons inside the menu
var $selectAll = $('<input type="checkbox"> Select/Unselect All</input>' );
//append the buttons inside the menu
$rendered.find('.select2-dropdown').prepend($selectAll);
$selectAll.on("click", function (e) {
var $results = self.$element.find("option").map(function (idx, ele) {
return ele.value;
});
if($(this).prop("checked") == true){
self.$element.val($results).trigger("change");
}
else{
self.$element.val(null).trigger("change");
}
self.trigger("close")
});
return $rendered;
};
$(".js-source-states").select2({
allowClear: true,
tag: false,
closeOnSelect: false,
placeholder: "Search",
dropdownAdapter: Utils.Decorate(
Utils.Decorate(
Dropdown,
AttachBody,
),
SelectAll
),
});
var placeHolderValue = `${previousSelectionCount}` ? previousSelectionCount : ' # options selected'
var $selectNumber = $(`<div class="counter"> ${placeHolderValue} options selected</div>`);
$(".js-source-states").after($selectNumber);
$(".js-source-states").on("change", function (e){
var selectedOptions = $(this).select2('data').length;
console.log('helllooooo', selectedOptions);
window.localStorage.setItem('selectCount', selectedOptions)
$(this).next(".counter").html(selectedOptions + ' options selected');
});
});
});
#import url("//cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/css/select2.min.css");
select{
width: 100%;
display: block;
margin: 0;
}
ul.select2-selection__rendered li.select2-selection__choice{
display: none !important;
}
.counter{
position: relative;
/* z-index: 100; */
display: block;
height: 34px;
border: 1px solid #ccc;
box-sizing: border-box;
padding: 8px 40px 8px 8px;
border-radius: 2px;
}
.select2-results__option.select2-results__option--selected{
background: blue;
}
.select2-results__option.select2-results__option--highlighted.select2-results__option--selectable
{
background: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/js/select2.full.min.js"></script>
<body>
<select class="js-source-states" multiple="multiple">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
</select>
<div>
<pre>
</pre>
</div>
<select class="js-source-states" multiple="multiple">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
</select>
</body>
You can store it like this:
localStorage.setItem("counter", document.getElementsByClassName("counter")[0]);
And you can load like this:
var save_count = localStorage.getItem("counter");
Yes, you are loading it correctly, but since you never saved it, you have nothing to load.
I want to show all the contents of select element (for below snippet) on focus when navigating to it using tab key.
select {
width: 200px;
border: 1px solid #aaa;
border-radius: 4px;
height: 28px;
overflow: hidden;
}
<select id="" class="select2" >
<option value="" disabled selected>Select Fruit</option>
<option value="1">Apple</option>
<option value="2">Banana</option>
</select>
A solution I've found in jQuery but I want the same function in plain JavaScript which I'm not able to do.
jQuery code :-
$('.select2').select2({
minimumResultsForSearch: 20
});
$(document).on('focus', '.select2.select2-container', function (e) {
var isOriginalEvent = e.originalEvent
var isSingleSelect = $(this).find(".select2-selection--single").length > 0
if (isOriginalEvent && isSingleSelect) {
$(this).siblings('select:enabled').select2('open');
}
});
Try something like
<select id="select2" class="select2" >
<option value="" disabled selected>Select Fruit</option>
<option value="1">Apple</option>
<option value="2">Banana</option>
</select>
document.getElementById("select2").addEventListener("focus", myFunction);
function myFunction() {
var e = document.getElementById("select2");
console.log(e.options[e.selectedIndex].value);
}
I have a drop down list of options which lets my users choose one of a few options. But I want to also include a button that when pressed will select a specific option out of the dropdown list.
This is working but the issue is that the dropdown list isnt showing the updated selection, but if you click on the dropdown list you can see that the selection the button chose is highlighted and is indeed selected.
function onclick() {
document.form.server_select.value = 'Quebec';
}
<select name="server_select" id="server_select">
<option value="random" selected>Auto Select</option>
<option value="Quebec">Quebec</option>
<option value="NewYork">NewYork</option>
<option value="Seattle">Seattle</option>
<option value="France">France</option>
</select>
<button onclick="onclick()">Button</button>
When you load the page the first option is displayed in the drop down to the user as seen
and
After pressing the button the dropdown still shows the first option in the list but when clicking onto the dropdown you can see a different option is selected.
I expected the dropdown to also show the new selection.
The code works as expected:
function change() {
document.getElementById('server_select').value = 'Quebec';
}
<form>
<select name="server_select" id="server_select">
<option value="random" selected>Auto Select</option>
<option value="Quebec">Quebec</option>
<option value="NewYork">NewYork</option>
<option value="Seattle">Seattle</option>
<option value="France">France</option>
</select>
</form>
<button onclick="change()">Button</button>
But looking at the screenshots, it looks like they are doing a custom dropdown, basically you are clicking on a transparent select, and they are updating their pretty dropdown manually, something like this:
function change() {
document.getElementById('server_select').value = 'Quebec';
}
function change2() {
element = document.getElementById('server_select')
element.value = 'Quebec';
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('change', true, true, window);
element.dispatchEvent(event);
}
function open() {
document.getElementById('server_select').value = 'Quebec';
}
document.getElementById('server_select').addEventListener('change', function(event) {
document.getElementById('value').innerHTML = event.target.value
})
#dropdown {
position: relative;
}
#server_select {
opacity: 0;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<form>
<div id="dropdown">
<span id="value">Auto Select</span>
<select name="server_select" id="server_select">
<option value="random" selected>Auto Select</option>
<option value="Quebec">Quebec</option>
<option value="NewYork">NewYork</option>
<option value="Seattle">Seattle</option>
<option value="France">France</option>
</select>
</div>
</form>
<button onclick="change()">Button</button>
<button onclick="change2()">Button Fixed</button>
You'll have to look at the actual HTML structure of your document to see what you need to update, but use the Button Fixed example to see (basically) what you need to do.
You should avoid using reserved words such as onclick as function name
for list of reserved words please look into https://www.w3schools.com/js/js_reserved.asp
function change() {
document.getElementById("server_select").value = "Quebec";
}
<select name="server_select" id="server_select">
<option value="random" selected>Auto Select</option>
<option value="Quebec">Quebec</option>
<option value="NewYork">NewYork</option>
<option value="Seattle">Seattle</option>
<option value="France">France</option>
</select>
<button onClick="change()">Button</button>
<script>
</script>
I have some JavaScript on a site I am building that I just can't get to not default when another script is used. Interestingly not all of the javascripts on the page cause the issue.
This is the script that I am using:
$(document).ready(function() {
$('.verdana').click(function(e) {
$('#changeMe').css('font-family','verdana');
e.preventDefault();
});
$('.arial').click(function(e) {
$('#changeMe').css('font-family','arial');
e.preventDefault();
});
$('.tahoma').click(function(e) {
$('#changeMe').css('font-family','tahoma');
e.preventDefault();
});
$('.times').click(function(e) {
$('#changeMe').css('font-family','times');
e.preventDefault();
});
$('.copperplatebold').click(function(e) {
$('#changeMe').css('font-family','copperplatebold');
e.preventDefault();
});
$('swiss721').click(function(e) {
$('#changeMe').css('font-family','swiss721');
e.preventDefault();
});
$('.baskerville').click(function(e) {
$('#changeMe').css('font-family','baskerville');
e.preventDefault();
});
$('.oldenglish').click(function(e) {
$('#changeMe').css('font-family','oldenglish');
e.preventDefault();
});
$('.timesnewroman').click(function(e) {
$('#changeMe').css('font-family','timesnewroman');
e.preventDefault();
});
$('.castellar').click(function(e) {
$('#changeMe').css('font-family','castellar');
e.preventDefault();
});
$('.calibri').click(function(e) {
$('#changeMe').css('font-family','calibri');
e.preventDefault();
});
$('.scriptmtbold').click(function(e) {
$('#changeMe').css('font-family','scriptmtbold');
e.preventDefault();
});
$('.lucidacal').click(function(e) {
e.preventDefault(e);
});
// select font in dropdown list to change font-family of #changeMe
$('select').change(function() {
if($(this).val() == "Default font"){
$('#changeMe').css('font-family',"");
} else {
$('#changeMe').css('font-family',$(this).val());
}
});
e.preventDefault(e);
});
Anyway I have tried putting "e.preventDefault(e);" in many places but no joy.
And another possible clue is that it seems to be my javascripts that also use drop down menus for selection that do it.
As always you're all stars for helping out! Thanks in advance!
HTML Elements that default the above script
<div style = "position: absolute; left: 160px; top: 490px;">
<select style="width: 150px;" id = "fonty">
<option selected="selected">Select Your Font....</option>
<option>Times New Roman</option>
<option>Verdana</option>
<option>Copper Plate Bold</option>
<option>Swiss721</option>
<option>Baskerville</option>
<option>OldEnglish</option>
<option>Castellar</option>
<option>Calibri</option>
<option>ScriptMTBold</option>
<option>LucidaCal</option>
<div style = "position: absolute; left: 160px; top: 440px;" >
<select id="selectcolor" name="selectcolor" style="width: 150px;">
<option value="null">Select Text Colour...</option>
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="darkblue">Dark Blue</option>
<option value="pink">Pink</option>
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="seagreen">Sea Green</option>
<option value="red">Red</option>
<option value="darkgreen">Dark Green</option>
<option value="bergundy">Bergundy</option>
<option value="cyan">Cyan</option>
<option value="magenta">Magenta</option>
<option value="mustard">mustard</option>
<option value="purple">Purple</option>
</select>
</div>
<div style = "position: absolute; left: 160px; top: 540px;">
<select id="category-navbar" name="category-navbar" style="width: 150px;">
<option value="">Motif Set One...</option>
<option value="H">motif 1</option>
<option value="rs">motif 2</option>
<option value="2">motif 3</option>
<option value="y">motif 4</option>
<option value="f">motif 5</option>
<option value="j">motif 6</option>
<option value="m">motif 7</option>
<option value="-,">motif 8</option>
<option value="[">motif 9</option>
<option value=";">motif 10</option>
<option value="V">motif 11</option>
<option value="N">motif 12</option>
<option value="R">motif 13</option>
<option value="]">motif 14</option>
<option value="F">motif 15</option>
<option value="t">motif 16</option>
<option value="">none...</option>
</select>
</div>
and the div for the text that I am affecting:
<!--The address div-->
<div class="selectcolor" style = "position: absolute; left: 425px; top: 360px;"id="changeMe">....please add you address using the box on the left</div>
For you click event handler for swiss721 you are selecting an element with the tag name swiss721, not a class name:
$('swiss721').click(function(e) { // This line
$('#changeMe').css('font-family','swiss721');
e.preventDefault();
});
You should add a period before the selector:
$('.swiss721').click(function (e) {
Additionally, the method preventDefault() does not take in any arguments, but you are passing one to it in a few cases at the end.
Lastly, you have an extraneous e.preventDefault() after your select handler.
After you posted your HTML
You're not being specific with your "select" selector. You have a number of elements, doing different things - only one of which holds values to font families.
Also, you haven't closed the first opening tag in your HTML.
First
It could be a script error being thrown. You have a stray e.preventDefault() at the bottom which isn't a part of any listener.
Second
If this is in an external script (it's own .js file) - make sure you DON'T have the tags in it. If the content is dynamic - Make sure that's considered when this script is loaded/executed.
$('.verdana') won't work because there is no element with a class 'verdana' (at least in your HTML you posted).
You have to listen for the change event on the select element (with id fonty) which contains all the fonts.
$("#fonty").change(function(event) {
var selectedFont = $(this).val();
if (selectedFont == "Verdana") {
$('#changeMe').css('font-family','verdana');
}
else if (selectedFont == "Copper Plate Bold") {
$('#changeMe').css('font-family','copperplatebold');
}
// ......
});
Enhancement suggestion:
you can shrink your javascript code if you set the value of each <option> so that it can be used as the font you pass to $('#changeMe').css("font-family", ...)
HMTL:
<select style="width: 150px;" id = "fonty">
<option selected="selected">Select Your Font....</option>
<option value="verdana">Verdana</option>
<option value="copperplatebold">Copper Plate Bold</option>
<option value="arial">Arial</option>
...
</select>
JS:
$("#fonty").change(function(event) {
var selectedFont = $(this).val();
$('#changeMe').css('font-family', selectedFont);
});