HTML5 Javascript Play/Pause button - javascript

I'm attempting to customise the control buttons on my video player. Currently I have a button that plays and pauses my video. This is working great. Though I want a visual representation of the play and pause buttons, instead of them staying the same when in the paused state or when the video is playing. I plan on having two seperate images for play and pause.
My problem is that I can't quite get my javascript to toggle my buttons, I'm thinking the best way to toggle the buttons is when one is paused, hide one element and when the video is playing hide the other element.
So here is what I have currently:
function playPause() {
mediaPlayer = document.getElementById('media-video');
if (mediaPlayer.paused)
mediaPlayer.play();
$('.play-btn').hide();
else
mediaPlayer.pause();
$('.pause-btn').hide();
}
Any help is greatly appreciated.

You need to use more Braces '{}' in if and else
function playPause() {
var mediaPlayer = document.getElementById('media-video');
if (mediaPlayer.paused) {
mediaPlayer.play();
$('.pause-btn').show();
$('.play-btn').hide();
} else {
mediaPlayer.pause();
$('.play-btn').show();
$('.pause-btn').hide();
}
}
I think it's works well.

For e.g.:
function togglePlayPause() {
// If the mediaPlayer is currently paused or has ended
if (mediaPlayer.paused || mediaPlayer.ended) {
// Change the button to be a pause button
changeButtonType(playPauseBtn, 'pause');
// Play the media
mediaPlayer.play();
}
// Otherwise it must currently be playing
else {
// Change the button to be a play button
changeButtonType(playPauseBtn, 'play');
// Pause the media
mediaPlayer.pause();
}}
Source: http://www.creativebloq.com/html5/build-custom-html5-video-player-9134473

/* in Jquery*/
$('#play-pause-button').click(function () {
if ($("#media-video").get(0).paused) {
$("#media-video").get(0).play();
}
else {
$("#media-video").get(0).pause();
}
});
Video is a DOM element not the javascript function;

Here are two examples, each comes with html, css and js.
const $ = (s, c = document) => c.querySelector(s);
const $$ = (s, c = document) => Array.prototype.slice.call(c.querySelectorAll(s));
function main(){
/* Example 1 */
// optional code to trigger click for label when 'Space' key pressed
$$('label.btn-toggle').forEach((label) => {
label.addEventListener('keypress', (e) => {
if(e.key === ' ' || e.code === 'Space'){
let input = e.target.control;
if(input){
input.click();
}
}
});
});
$('#btnPlayPause>input[type="checkbox"]').addEventListener('click', (e) => {
let input = e.target;
if(input.parentNode.getAttribute('aria-disabled') === 'true'){
e.preventDefault();
return;
}
if(input.checked){
// TODO play
console.log('playing');
}else{
// TODO pause
console.log('paused');
}
});
/* Example 2 */
$('#btnMuteUnmute').addEventListener('click', (e) => {
let button = e.target;
let isOn = button.value==='on';
if(!isOn){
// TODO mute
console.log('muted');
}else{
// TODO unmute
console.log('unmuted');
}
button.value = isOn?'off':'on';
});
}
document.addEventListener('DOMContentLoaded', main);
/* Example 1 */
label.btn-toggle{
font-size: 13.3333px;
font-family: sans-serif;
display: inline-flex;
flex-flow: row wrap;
align-content: center;
justify-content: center;
cursor: default;
box-sizing: border-box;
margin: 0px;
padding: 1px 6px;
background-color: #efefef;
color: buttontext;
border: 1px solid buttonborder;
border-radius: 2px;
user-select: none;
}
label.btn-toggle:hover{
background-color: #dfdfdf;
}
label.btn-toggle:active{
background-color: #f5f5f5;
}
.btn-toggle>input[type="checkbox"]:not(:checked)~.on-text{
display: none;
}
.btn-toggle>input[type="checkbox"]:checked~.off-text{
display: none;
}
#btnPlayPause{
width: 60px;
height: 60px;
}
/* Example 2 */
button.btn-toggle[value="on"]::after{
content: attr(data-on-text);
}
button.btn-toggle[value="off"]::after{
content: attr(data-off-text);
}
#btnMuteUnmute{
width: 60px;
height: 60px;
}
<!-- Example 1 -->
<label id="btnPlayPause" role="button" class="btn-toggle" tabindex="0" title="Play / Pause">
<input type="checkbox" tabindex="-1" autocomplete="off" hidden aria-hidden="true" />
<span class="on-text">Pause</span>
<span class="off-text">Play</span>
</label>
<!-- Example 2 -->
<button id="btnMuteUnmute" type="button" class="btn-toggle"
value="off" data-on-text="Unmute" data-off-text="Mute" title="Mute / Unmute"></button>

Related

Input checkbox not firing javascript for data-theme attribute

I'm trying to accomplish a few things to get dark mode working on my site.
Use a checkbox to switch between light and dark themes (the checkbox will set the data-theme attribute to user's preference). Here't the js below
function detectColorScheme() {
var theme="light";
//default to light
//local storage is used to override OS theme settings
if(localStorage.getItem("theme")){
if(localStorage.getItem("theme") == "dark"){
var theme = "dark";
}
} else if(!window.matchMedia) {
//matchMedia method not supported
return false;
} else if(window.matchMedia("(prefers-color-scheme: dark)").matches) {
//OS theme setting detected as dark
var theme = "dark";
}
//dark theme preferred, set document with a `data-theme` attribute
if (theme=="dark") {
document.documentElement.setAttribute("data-theme", "dark");
}
}
detectColorScheme();
//identify the toggle switch HTML element
const themeSwitch = document.getElementById('hm-theme-switch-toggle');
//function that changes the theme, and sets a localStorage variable to track the theme between page loads
function switchTheme(e) {
if (e.target.checked) {
localStorage.setItem('theme', 'dark');
document.documentElement.setAttribute('data-theme', 'dark');
themeSwitch.checked = true;
} else {
localStorage.setItem('theme', 'light');
document.documentElement.setAttribute('data-theme', 'light');
themeSwitch.checked = false;
}
}
//listener for changing themes
themeSwitch.addEventListener('change', switchTheme, false);
//pre-check the dark-theme checkbox if dark-theme is set
if (document.documentElement.getAttribute("data-theme") == "dark"){
themeSwitch.checked = true;
}
My html and css is setup that I have a pseudo element to change the text if the checkbox is checked, along with the entire theme changing to dark mode. For some reason it's not firing though even though I have the label pointed to the input id and the correct id is called in js.
<div class="hm-theme-switch-wrapper">
<input type="checkbox" class="hm-theme-toggle" id="hm-theme-switch-toggle" name="hm-checkbox" />
<label for="hm-theme-switch-toggle" id="hm-theme-switch" style="text-align:right;"><i class="hm-theme-state-icon"></i><span>Dark</span></label>
</div>
.hm-theme-switch-wrapper {
background-color: none;
border-radius: 150px;
border: 2px solid var(--hm-color-text);
overflow: auto;
float: right;
width: 100px;
label {
display: flex;
align-items: center;
padding: 5px 10px;
margin: 0;
}
input.hm-theme-toggle {
display: none;
}
input#hm-theme-switch-toggle:checked + label span {
display: none;
}
input#hm-theme-switch-toggle:checked + label:after {
content: "Light";
}
.hm-theme-state-icon {
background-image : url(https://michaelcraig.design/wp-content/uploads/2021/04/light_dark.svg);
background-size: cover;
display: inline-block;
height: 20px;
width: 20px;
margin-right: 10px;
}
.hm-theme-state {
text-align:center;
display:block;
border-radius:4px;
color: var(--hm-color-text);
font-size: 16px;
font-weight: 600;
}
}
I appreciate any help and suggestions. You can also view this live # https://michaelcraig.design
Try put this lines:
const themeSwitch = document.getElementById("hm-theme-switch-toggle");
themeSwitch.addEventListener("change", switchTheme, false);
.. inside a ready trigger:
$(document).ready(function(){
const themeSwitch = document.getElementById("hm-theme-switch-toggle");
themeSwitch.addEventListener("change", switchTheme, false);
});
Maybe DOM is not ready when getElementById run.
Edit: Since OP is not using jQuery, here's the vanilla JS equivalent:
document.addEventListener('DOMContentLoaded', () => {
const themeSwitch = document.getElementById("hm-theme-switch-toggle");
themeSwitch.addEventListener("change", switchTheme, false);
});

Dark mode - how to handle the auto preference

In this darkmode code I allow the user to set the theme through system preferences while also allowing the user to override the system preferred theme by toggling the button or radio.
How do I set checked state for the system default radio when the user changes their system preference to auto?
Since it changes prefers-color-scheme to either light or dark how would I detect the user changing their preference to auto in order to update the radio's checked state? I tried adding the checked state inside of if (window.matchMedia("(prefers-color-scheme: no-preference)").matches) {} but it didn't execute.
Also I can't figure out why my window.addEventListener("load", (e) => {} isn't detecting the user selected theme on load. It's defaulting to light even when the page is refreshed and the theme in settings is set to dark.
https://codepen.io/moofawsaw/pen/VwmaPMV
$(document).ready(function() {
function setLight() {
$("body").removeClass("dark-theme");
$("body").addClass("light-theme");
$("#light").prop("checked", true);
$('input[name="theme"]').change();
}
function setDark() {
$("body").addClass("dark-theme");
$("body").removeClass("light-theme");
$("#dark").prop("checked", true);
$('input[name="theme"]').change();
}
function setMode() {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
$("#dark").prop("checked", true);
$('input[name="theme"]').change();
setDark();
} else {
$("#light").prop("checked", true);
$('input[name="theme"]').change();
setLight();
}
}
//Check the mode on load and style accordingly
if (localStorage.getItem("mode") == "dark-theme") {
setDark();
} else {
setLight();
}
//Check for when system default is changed -> change theme
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", (e) => {
if (localStorage.getItem("mode") !== null) {
//Manually set so don't do anything
} else {
setMode();
}
});
window.addEventListener("load", (e) => {
//If the mode is mannually set on load - choose that mode
if (localStorage.getItem("mode") !== null) {
// Do nothing the mode has been set manually
} else {
// Set the mode to the default
setMode();
}
});
//add toggle
$("#toggleTheme").on("click", function() {
if ($("body").hasClass("dark-theme")) {
localStorage.setItem("mode", "light-theme");
setLight();
} else {
localStorage.setItem("mode", "dark-theme");
setDark();
}
});
$("#light").on("click", function() {
localStorage.setItem("mode", "light-theme");
setLight();
});
$("#dark").on("click", function() {
localStorage.setItem("mode", "dark-theme");
setDark();
});
$("#default").on("click", function() {
localStorage.removeItem("mode");
if (localStorage.getItem("mode") !== null) {
setMode();
}
});
});
//For selecting radio
$('input[name="theme"]').on("change", function() {
if ($(this).is(":checked")) {
$("label.checked").removeClass("checked");
$(this).closest("label").addClass("checked");
}
});
body {
--font-color: blue;
--bg-color: white;
--bg-span: #ececec;
}
body.dark-theme {
--font-color: white;
--bg-color: black;
--bg-span: white;
}
#media (prefers-color-scheme: dark) {
body {
--font-color: white;
--bg-color: black;
--bg-span: white;
}
body.light-theme {
--font-color: blue;
--bg-color: white;
--bg-span: #ececec;
}
}
body {
color: var(--font-color);
background: var(--bg-color);
}
button {
padding: 0.3rem 0.9rem;
outline: none;
color: var(--font-color);
background: var(--bg-color);
}
span {
padding: 0.9rem;
color: var(--font-color);
background: var(--bg-span);
}
img {
max-width: 190px;
}
/*input {
display: none;
}*/
label {
overflow: hidden;
display: flex;
flex-direction: column;
margin-right: 0.9rem;
border: 1px solid whitesmoke;
border-radius: 9px;
}
label.checked {
border: 3px solid blue;
}
.theme {
display: flex;
}
.buttons,
.theme {
padding: 1.3rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="buttons">
<button id="toggleTheme">Mode</button>
</div>
<div class="theme">
<label for="light">
<img src="https://github.githubassets.com/images/modules/settings/color_mode_light.svg">
<input type="radio" name="theme" id="light">
<span>Light</span>
</label>
<label for="dark">
<img src="https://github.githubassets.com/images/modules/settings/color_mode_dark.svg">
<input type="radio" name="theme" id="dark">
<span>Dark</span>
</label>
<label for="default">
<img src="https://github.githubassets.com/images/modules/settings/color_mode_auto.svg">
<input type="radio" name="theme" id="default">
<span>System Default</span>
</label>
</div>
The feature no-preference of the prefers-color-scheme #media rule is deprecated and that's why it does not work any more on latest browsers.
The load window event does execute but it doesn't have the appropriate logic in your code. Your code does nothing if the mode local storage setting is not null, which of course is the case after selecting something.
You should have the following behaviours regarding mode setting:
light for light scheme that will override system/browser setting
dark for dark scheme that will override system/browser setting
Anything elese other than dark/light, including null/undefined, will apply what browser setting has, which it can have its own override or reading the OS setting
Also, setLight/setDark procedures should just apply the theme and not alter any input elements state because it will end up with circular value setting bugs:
function setLight() {
$("body").removeClass("dark-theme");
$("body").addClass("light-theme");
}
function setDark() {
$("body").addClass("dark-theme");
$("body").removeClass("light-theme");
}
Instead, you can have all the inputs change logic inside setMode which should check mode setting and handle all logic like this:
function setMode() {
// have a variable to indicate what mode
// we should apply at the end of the procedure
let lightMode;
// always unregister media listener,
// because we only need it if mode is not set,
// which then we'll have to read media queries using matchMedia
unregisterMediaListener();
switch (localStorage.getItem("mode")) {
case 'light-theme': {
lightMode = true;
$("#light").prop("checked", true);
break;
}
case 'dark-theme': {
lightMode = false;
$("#dark").prop("checked", true);
break;
}
default: { // using system setting
$("#default").prop("checked", true);
// set lightMode indicator using the matchMedia query result
lightMode = window.matchMedia("(prefers-color-scheme: light)").matches;
// and register media change listener for changes
registerMediaListener();
}
}
// allpy new input values
$('input[name="theme"]').change();
// set the actual mode
if (lightMode) {
setLight();
} else {
setDark();
}
}
And finally the matchMedia prefers-color-scheme: light change listener:
// we set a mediaMatch variable so we can use it and unregister the listener
let mm;
function registerMediaListener() {
mm = window.matchMedia("(prefers-color-scheme: light)");
mm.addEventListener('change', onLightSchemeChange);
}
function unregisterMediaListener() {
if (mm) mm.removeListener(onLightSchemeChange);
}
function onLightSchemeChange(scheme) {
if (scheme.matches) {
// We have browser/system light scheme
setLight();
} else {
setDark();
}
}
Working example
You can check this forked and modified pen that is actually working and does select the appropriate setting/option when the page loads: https://codepen.io/clytras/pen/MWberor

How to create a shift key + mouse click event that would change the color of a black button to a yellow button on click? JavaScript

I am creating a minesweeper game and am trying to create an event where if the user holds down the shift key and left clicks their mouse simultaneously then the button (background-color is black) that I created for the field will turn yellow to indicate a button that is flagged. Here is what I have so far. The attribute ('data-value', 0) means that that button does not have a mine or number label that will indicate how far it is from the mine.
JS:
$('button').getAttribute('data-value', 0).getAttribute('data-x', j).getAttribute('data-y', i).getAttribute('data-visible', false).getAttribute('data-mine', false).click(function (e) {
if (e.shiftKey) {
$('button').addClass('flag');
}
});
CSS:
table td button {
background-color: black;
color: white;
width: 2em;
height: 2em;
}
.flag {
background-color: yellow;
}
Thank you for your help.
If you are not able to detect the key combination you can use the following script to do that, see below code try pressing SHIFT+ mouse left click to detect it.
let ShiftOn = false;
$(document).ready(function() {
$(document).keydown(function(e) {
let isShiftOn = e.which == "16";
(isShiftOn) && (ShiftOn = true);
}).keyup(function() {
ShiftOn = false;
});
$("#detectable-area").on('click', function() {
(ShiftOn) && console.log('SHIFT +LEFT Click');
});
});
div#detectable-area {
width: 100%;
height: 250px;
background: #c8c8c8;
vertical-align: middle;
text-align: center;
line-height: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="detectable-area">Press SHIFT + click anywhere in the div to detect.</div>

Hovering Option in Select-field not working [duplicate]

I am trying to show a description when hovering over an option in a select list, however, I am having trouble getting the code to recognize when hovering.
Relevant code:
Select chunk of form:
<select name="optionList" id="optionList" onclick="rankFeatures(false)" size="5"></select>
<select name="ranks" id="ranks" size="5"></select>
Manipulating selects (arrays defined earlier):
function rankFeatures(create) {
var $optionList = $("#optionList");
var $ranks = $("#ranks");
if(create == true) {
for(i=0; i<5; i++){
$optionList.append(features[i]);
};
}
else {
var index = $optionList.val();
$('#optionList option:selected').remove();
$ranks.append(features[index]);
};
}
This all works. It all falls apart when I try to deal with hovering over options:
$(document).ready(
function (event) {
$('select').hover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
I found that code while searching through Stack Exchange, yet I am having no luck getting it to work. The alert occurs when I click on an option. If I don't move the mouse and close the alert by hitting enter, it goes away. If I close out with the mouse a second alert window pops up. Just moving the mouse around the select occasionally results in an alert box popping up.
I have tried targeting the options directly, but have had little success with that. How do I get the alert to pop up if I hover over an option?
You can use the mouseenter event.
And you do not have to use all this code to check if the element is an option.
Just use the .on() syntax to delegate to the select element.
$(document).ready(function(event) {
$('select').on('mouseenter','option',function(e) {
alert('yeah');
// this refers to the option so you can do this.value if you need..
});
});
Demo at http://jsfiddle.net/AjfE8/
try with mouseover. Its working for me. Hover also working only when the focus comes out from the optionlist(like mouseout).
function (event) {
$('select').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
You don't need to rap in in a function, I could never get it to work this way. When taking it out works perfect. Also used mouseover because hover is ran when leaving the target.
$('option').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
console.log('yeah!');
};
})​
Fiddle to see it working. Changed it to console so you don't get spammed with alerts. http://jsfiddle.net/HMDqb/
That you want is to detect hover event on option element, not on select:
$(document).ready(
function (event) {
$('#optionList option').hover(function(e) {
console.log(e.target);
});
})​
I have the same issue, but none of the solutions are working.
$("select").on('mouseenter','option',function(e) {
$("#show-me").show();
});
$("select").on('mouseleave','option',function(e) {
$("#show-me").hide();
});
$("option").mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
});
Here my jsfiddle https://jsfiddle.net/ajg99wsm/
I would recommend to go for a customized variant if you like to ease
capture hover events
change hover color
same behavior for "drop down" and "all items" view
plus you can have
resizeable list
individual switching between single selection and multiple selection mode
more individual css-ing
multiple lines for option items
Just have a look to the sample attached.
$(document).ready(function() {
$('.custopt').addClass('liunsel');
$(".custopt, .custcont").on("mouseover", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "block")
} else {
$(this).addClass("lihover");
}
})
$(".custopt, .custcont").on("mouseout", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "none")
} else {
$(this).removeClass("lihover");
}
})
$(".custopt").on("click", function(e) {
$(".custopt").removeClass("lihover");
if ($("#btsm").val() == "ssm") {
//single select mode
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
$(this).removeClass("liunsel");
$(this).addClass("lisel");
} else if ($("#btsm").val() == "msm") {
//multiple select mode
if ($(this).is(".lisel")) {
$(this).addClass("liunsel");
$(this).removeClass("lisel");
} else {
$(this).addClass("lisel");
$(this).removeClass("liunsel");
}
}
updCustHead();
});
$(".custbtn").on("click", function() {
if ($(this).val() == "ssm") {
$(this).val("msm");
$(this).text("switch to single-select mode")
} else {
$(this).val("ssm");
$(this).text("switch to multi-select mode")
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
}
updCustHead();
});
function updCustHead() {
if ($("#btsm").val() == "ssm") {
if ($(".lisel").length <= 0) {
$("#hrnk").text("current selected option");
} else {
$("#hrnk").text($(".lisel").text());
}
} else {
var numopt = +$(".lisel").length,
allopt = $(".custopt").length;
$("#hrnk").text(numopt + " of " + allopt + " selected option" + (allopt > 1 || numopt === 0 ? 's' : ''));
}
}
});
body {
text-align: center;
}
.lisel {
background-color: yellow;
}
.liunsel {
background-color: lightgray;
}
.lihover {
background-color: coral;
}
.custopt {
margin: .2em 0 .2em 0;
padding: .1em .3em .1em .3em;
text-align: left;
font-size: .7em;
border-radius: .4em;
}
.custlist,
.custhead {
width: 100%;
text-align: left;
padding: .1em;
border: LightSeaGreen solid .2em;
border-radius: .4em;
height: 4em;
overflow-y: auto;
resize: vertical;
user-select: none;
}
.custlist {
display: none;
cursor: pointer;
}
.custhead {
resize: none;
height: 2.2em;
font-size: .7em;
padding: .1em .4em .1em .4em;
margin-bottom: -.2em;
width: 95%;
}
.custcont {
width: 7em;
padding: .5em 1em .6em .5em;
/* border: blue solid .2em; */
margin: 1em auto 1em auto;
}
.custbtn {
font-size: .7em;
width: 105%;
}
h3 {
margin: 1em 0 .5em .3em;
font-weight: bold;
font-size: 1em;
}
ul {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>
customized selectable, hoverable resizeable dropdown with multi-line, single-selection and multiple-selection support
</h3>
<div id="crnk" class="custcont">
<div>
<button id="btsm" class="custbtn" value="ssm">switch to multi-select mode</button>
</div>
<div id="hrnk" class="custhead">
current selected option
</div>
<ul id="ranks" class="custlist">
<li class="custopt">option one</li>
<li class="custopt">option two</li>
<li class="custopt">another third long option</li>
<li class="custopt">another fourth long option</li>
</ul>
</div>

Hovering over an <option> in a select list

I am trying to show a description when hovering over an option in a select list, however, I am having trouble getting the code to recognize when hovering.
Relevant code:
Select chunk of form:
<select name="optionList" id="optionList" onclick="rankFeatures(false)" size="5"></select>
<select name="ranks" id="ranks" size="5"></select>
Manipulating selects (arrays defined earlier):
function rankFeatures(create) {
var $optionList = $("#optionList");
var $ranks = $("#ranks");
if(create == true) {
for(i=0; i<5; i++){
$optionList.append(features[i]);
};
}
else {
var index = $optionList.val();
$('#optionList option:selected').remove();
$ranks.append(features[index]);
};
}
This all works. It all falls apart when I try to deal with hovering over options:
$(document).ready(
function (event) {
$('select').hover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
I found that code while searching through Stack Exchange, yet I am having no luck getting it to work. The alert occurs when I click on an option. If I don't move the mouse and close the alert by hitting enter, it goes away. If I close out with the mouse a second alert window pops up. Just moving the mouse around the select occasionally results in an alert box popping up.
I have tried targeting the options directly, but have had little success with that. How do I get the alert to pop up if I hover over an option?
You can use the mouseenter event.
And you do not have to use all this code to check if the element is an option.
Just use the .on() syntax to delegate to the select element.
$(document).ready(function(event) {
$('select').on('mouseenter','option',function(e) {
alert('yeah');
// this refers to the option so you can do this.value if you need..
});
});
Demo at http://jsfiddle.net/AjfE8/
try with mouseover. Its working for me. Hover also working only when the focus comes out from the optionlist(like mouseout).
function (event) {
$('select').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
You don't need to rap in in a function, I could never get it to work this way. When taking it out works perfect. Also used mouseover because hover is ran when leaving the target.
$('option').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
console.log('yeah!');
};
})​
Fiddle to see it working. Changed it to console so you don't get spammed with alerts. http://jsfiddle.net/HMDqb/
That you want is to detect hover event on option element, not on select:
$(document).ready(
function (event) {
$('#optionList option').hover(function(e) {
console.log(e.target);
});
})​
I have the same issue, but none of the solutions are working.
$("select").on('mouseenter','option',function(e) {
$("#show-me").show();
});
$("select").on('mouseleave','option',function(e) {
$("#show-me").hide();
});
$("option").mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
});
Here my jsfiddle https://jsfiddle.net/ajg99wsm/
I would recommend to go for a customized variant if you like to ease
capture hover events
change hover color
same behavior for "drop down" and "all items" view
plus you can have
resizeable list
individual switching between single selection and multiple selection mode
more individual css-ing
multiple lines for option items
Just have a look to the sample attached.
$(document).ready(function() {
$('.custopt').addClass('liunsel');
$(".custopt, .custcont").on("mouseover", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "block")
} else {
$(this).addClass("lihover");
}
})
$(".custopt, .custcont").on("mouseout", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "none")
} else {
$(this).removeClass("lihover");
}
})
$(".custopt").on("click", function(e) {
$(".custopt").removeClass("lihover");
if ($("#btsm").val() == "ssm") {
//single select mode
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
$(this).removeClass("liunsel");
$(this).addClass("lisel");
} else if ($("#btsm").val() == "msm") {
//multiple select mode
if ($(this).is(".lisel")) {
$(this).addClass("liunsel");
$(this).removeClass("lisel");
} else {
$(this).addClass("lisel");
$(this).removeClass("liunsel");
}
}
updCustHead();
});
$(".custbtn").on("click", function() {
if ($(this).val() == "ssm") {
$(this).val("msm");
$(this).text("switch to single-select mode")
} else {
$(this).val("ssm");
$(this).text("switch to multi-select mode")
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
}
updCustHead();
});
function updCustHead() {
if ($("#btsm").val() == "ssm") {
if ($(".lisel").length <= 0) {
$("#hrnk").text("current selected option");
} else {
$("#hrnk").text($(".lisel").text());
}
} else {
var numopt = +$(".lisel").length,
allopt = $(".custopt").length;
$("#hrnk").text(numopt + " of " + allopt + " selected option" + (allopt > 1 || numopt === 0 ? 's' : ''));
}
}
});
body {
text-align: center;
}
.lisel {
background-color: yellow;
}
.liunsel {
background-color: lightgray;
}
.lihover {
background-color: coral;
}
.custopt {
margin: .2em 0 .2em 0;
padding: .1em .3em .1em .3em;
text-align: left;
font-size: .7em;
border-radius: .4em;
}
.custlist,
.custhead {
width: 100%;
text-align: left;
padding: .1em;
border: LightSeaGreen solid .2em;
border-radius: .4em;
height: 4em;
overflow-y: auto;
resize: vertical;
user-select: none;
}
.custlist {
display: none;
cursor: pointer;
}
.custhead {
resize: none;
height: 2.2em;
font-size: .7em;
padding: .1em .4em .1em .4em;
margin-bottom: -.2em;
width: 95%;
}
.custcont {
width: 7em;
padding: .5em 1em .6em .5em;
/* border: blue solid .2em; */
margin: 1em auto 1em auto;
}
.custbtn {
font-size: .7em;
width: 105%;
}
h3 {
margin: 1em 0 .5em .3em;
font-weight: bold;
font-size: 1em;
}
ul {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>
customized selectable, hoverable resizeable dropdown with multi-line, single-selection and multiple-selection support
</h3>
<div id="crnk" class="custcont">
<div>
<button id="btsm" class="custbtn" value="ssm">switch to multi-select mode</button>
</div>
<div id="hrnk" class="custhead">
current selected option
</div>
<ul id="ranks" class="custlist">
<li class="custopt">option one</li>
<li class="custopt">option two</li>
<li class="custopt">another third long option</li>
<li class="custopt">another fourth long option</li>
</ul>
</div>

Categories