In HTML5 I have a dropdown menu . When choosing different options I hide or show different parts of my page. Here is that script:
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
However what I want to do now, in another script is to preload an option from the dropdown. I can do it easily with this script:
setSelectedIndex(document.getElementById('target'),'content_1');
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
This is where my problem comes up, my dropdow will get the value I want, but the part that I want to be shown when choosing that option won't come up.
That is because change events need to happen from the browser.
When the user commits the change explicitly (e.g. by selecting a value
from a 's dropdown with a mouse click, by selecting a date
from a date picker for , by selecting a file in the
file picker for , etc.);
If your using Jquery you can:
$("#id").val("value").trigger('change');
or you can use javascript if your not worried about building the event object:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
I would recommend moving your anonymous onchange function into a named function that you can call once onload, and again onchange.
Here is the function I wrote:
function setContent(id) {
//get the current visible content
var vis = document.querySelector('.vis');
//get the target element by id
var target = document.getElementById(id);
//make current vis element inv
if (vis) vis.className = "inv";
//make target element vis
if (target) target.className = 'vis';
}
and a fiddle
edited: got rid of querySelectorAll to stick closer to OP original code and updated fiddle. clarified and commented code.
The problem you have is changing a vale or the selected value of an input with JavaScript does not trigger any change event. So you would need to manually trigger the event.
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
//Setting the selected value with JavaScript does not trigger the change event so you need to manually trigger the change event
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
s.dispatchEvent(evt);
} else {
s.fireEvent("onchange");
}
return;
}
Related
I have some HTML tabs which use radio buttons to control them. However I am using a select drop down menu with some javascript to control them on mobile screen sizes.
// Get select element for mobile navigation
const select = document.getElementById("location");
// Event listener for selecting tabs event for mobile
select.addEventListener("change", (e) => {
const target = e.target.value;
const venueTabs = document.querySelectorAll(".tabs__radio");
for (let i = 0; i < venueTabs.length; i++) {
if (venueTabs[i].id === target) {
venueTabs[i].setAttribute("checked", "checked");
console.log(venueTabs[i], target);
} else if (venueTabs[i].id !== target) {
venueTabs[i].removeAttribute("checked");
}
}
});
My eventListener seems to work and is logging out what is expected. It compares the tab div id to the event target.
However this only seems to work when I test each select option twice, on the 3rd attempt the tabbed content disappears (css switches to display: none).
I can't seem to work out what is causing the error.
I have set up a code sandbox with my code https://codesandbox.io/s/nice-ramanujan-2yq1r?file=/src/index.js to help debug it. If the drop down menus isn't showing, you may have to view it for mobile/ below 700px wide & it'll display the select drop down menu.
Can anyone help identify what is causing this bug? I previously had hard coded the EventListener that worked perfectly, it looked like this
select.addEventListener("change", (e) => {
const target = e.target;
const tabone = document.getElementById("tab0");
const tabtwo = document.getElementById("tab1");
const tabthree = document.getElementById("tab2");
const tabfour = document.getElementById("tab3");
if (target.value === "tab0") {
tabtwo.removeAttribute("checked");
tabthree.removeAttribute("checked");
tabfour.removeAttribute("checked");
tabone.setAttribute("checked", "checked");
} else if (target.value === "tab1") {
tabthree.removeAttribute("checked");
tabfour.removeAttribute("checked");
tabone.removeAttribute("checked");
tabtwo.setAttribute("checked", "checked");
} else if (target.value === "tab2") {
tabfour.removeAttribute("checked");
tabone.removeAttribute("checked");
tabtwo.removeAttribute("checked");
tabthree.setAttribute("checked", "checked");
} else if (target.value === "tab3") {
tabone.removeAttribute("checked");
tabtwo.removeAttribute("checked");
tabthree.removeAttribute("checked");
tabfour.setAttribute("checked", "checked");
}
});
However it's not dynamic enough to take any number of tabs that may exist.
This doesn't need any looping over all the radio buttons to begin with - just select the one element you want to set checked via its id:
select.addEventListener("change", (e) => {
const target = e.target.value;
const venueTab = document.querySelector("#"+target);
venueTab.checked = true;
});
I have a SELECT element that I am replacing with a dropdown. I have successfully created the dropdown from the SELECT and child OPTION elements, but I need to add a click event.
This click event would be as such:
If LI is clicked, also click corresponding OPTION.
This is because Woocommerce must have some JS or PHP working where depending on the option, it shows stock status and variable amount. As such, I assume that the click event will also bind the OPTION value to the form for adding to cart.
I have this JS code:
window.onload = main;
function main(){
var select = document.querySelector('.turnintodropdown');
var selsOpts = document.querySelector('.turnintodropdown option');
var selsLi = document.querySelector('.selectOption');
var trigger = document.createElement('a');
var openDropdown = 'dropdownVisible';
var closeDropdown = 'dropdownHidden';
(function addDropdown() {
if(select) {
var selsCon = document.createElement('div');
var selsOuter = document.createElement('ul');
selsCon.classList.add('selectContainer');
selsOuter.classList.add('selectOuter');
select.parentNode.insertBefore(selsCon, select);
selsCon.appendChild(selsOuter);
for(var i=0; i<select.length; i++) {
if(select.childNodes[i].classList.contains('enabled') || select.childNodes[i].innerHTML == '- -'){ // Select First Child and <option> Tags with Enabled Class
// Create New Elements
var optsNew = document.createElement('li');
optsNew.innerHTML = select.childNodes[i].text;
optsNew.classList.add('selectOption');
// Set Attributes to New Elements
if(optsNew.innerHTML !== '- -') {
optsNew.setAttribute('value', select.childNodes[i].text);
}
else {
void(0);
}
optsNew.click(clickFunc);
// Add New LI <option> to UL <container>
selsOuter.appendChild(optsNew);
// Click Events
console.log(select.firstChild);
}
}
var clickFunc = function() {
select.click();
};
select.style.display = 'none';
}
})();
}
Any help would be greatly appreciated.
Regards
Michael
I was a bit long to answer, sorry.
the function was originally taken from this webpage and not modified, it is supposed to work with most old browsers. I actually tested on last versions of Firefox / Chrome / Opera / Edge with success.
The version which handles all types of events is more complicated because you have to make cases for standard events to process them by type (not all are MouseEvents).
It also supports the inline functions, with onclick= in the html tag, and works also for events set with jQuery.
Note that if you want the same support for old broswers, you'll have to differentiate cases for the setting of events too, the modern addEventListener being not supported by all.
function fireClick(node){
if ( document.createEvent ) {
var evt = document.createEvent('MouseEvents');
evt.initEvent('click', true, false);
node.dispatchEvent(evt);
} else if( document.createEventObject ) {
node.fireEvent('onclick') ;
} else if (typeof node.onclick == 'function' ) {
node.onclick();
}
}
used like this for example:
fireClick(document.getElementById("myId"));
Vanilla JS (without jQuery)
/**
* Simulate a click event.
* #public
* #param {Element} elem the element to simulate a click on
*/
var simulateClick = function (elem) {
// Create our event (with options)
var evt = new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
});
// If cancelled, don't dispatch our event
var canceled = !elem.dispatchEvent(evt);
};
To use it, call the function, passing in the element you want to simulate the click on.
var someLink = document.querySelector('a');
simulateClick(someLink);
src / full article: https://gomakethings.com/how-to-simulate-a-click-event-with-javascript/
I'm using this awesome bouncy filter from Codyhouse but i can't for the life of me figure out how to make it run automatically i.e flip on its own and still accept user click events. The jsfiddle...Thanks.
jQuery(document).ready(function($) {
//wrap each one of your filter in a .cd-gallery-container
bouncy_filter($('.cd-gallery-container'));
function bouncy_filter($container) {
$container.each(function() {
var $this = $(this);
var filter_list_container = $this.children('.cd-filter'),
filter_values = filter_list_container.find('li:not(.placeholder) a'),
filter_list_placeholder = filter_list_container.find('.placeholder a'),
filter_list_placeholder_text = filter_list_placeholder.text(),
filter_list_placeholder_default_value = 'Select',
gallery_item_wrapper = $this.children('.cd-gallery').find('.cd-item-wrapper');
//store gallery items
var gallery_elements = {};
filter_values.each(function() {
var filter_type = $(this).data('type');
gallery_elements[filter_type] = gallery_item_wrapper.find('li[data-type="' + filter_type + '"]');
});
//detect click event
filter_list_container.on('click', function(event) {
event.preventDefault();
//detect which filter item was selected
var selected_filter = $(event.target).data('type');
//check if user has clicked the placeholder item (for mobile version)
if ($(event.target).is(filter_list_placeholder) || $(event.target).is(filter_list_container)) {
(filter_list_placeholder_default_value == filter_list_placeholder.text()) ? filter_list_placeholder.text(filter_list_placeholder_text): filter_list_placeholder.text(filter_list_placeholder_default_value);
filter_list_container.toggleClass('is-open');
//check if user has clicked a filter already selected
} else if (filter_list_placeholder.data('type') == selected_filter) {
filter_list_placeholder.text($(event.target).text());
filter_list_container.removeClass('is-open');
} else {
//close the dropdown (mobile version) and change placeholder text/data-type value
filter_list_container.removeClass('is-open');
filter_list_placeholder.text($(event.target).text()).data('type', selected_filter);
filter_list_placeholder_text = $(event.target).text();
//add class selected to the selected filter item
filter_values.removeClass('selected');
$(event.target).addClass('selected');
//give higher z-index to the gallery items selected by the filter
show_selected_items(gallery_elements[selected_filter]);
//rotate each item-wrapper of the gallery
//at the end of the animation hide the not-selected items in the gallery amd rotate back the item-wrappers
// fallback added for IE9
var is_explorer_9 = navigator.userAgent.indexOf('MSIE 9') > -1;
if (is_explorer_9) {
hide_not_selected_items(gallery_elements, selected_filter);
gallery_item_wrapper.removeClass('is-switched');
} else {
gallery_item_wrapper.addClass('is-switched').eq(0).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
hide_not_selected_items(gallery_elements, selected_filter);
gallery_item_wrapper.removeClass('is-switched');
});
}
}
});
});
}
});
function show_selected_items(selected_elements) {
selected_elements.addClass('is-selected');
}
function hide_not_selected_items(gallery_containers, filter) {
$.each(gallery_containers, function(key, value) {
if (key != filter) {
$(this).removeClass('is-visible is-selected').addClass('is-hidden');
} else {
$(this).addClass('is-visible').removeClass('is-hidden is-selected');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm assuming by "make it run automatically" you're talking about triggering the content-selection animation programatically, rather than requiring a user click. One possible solution is to assign an id to the selection elements, and then register the click handler directly to those elements, rather than the parent filter_list_container. Then, you can use jQuery's trigger() method to simulate a click on the appropriate element.
Assign an id in the html like this:
<a id="green" href="#0">Green</a>
Then register the click handler like this:
$("#red, #green, #blue").on('click', function(event){ ... }
...and trigger like this:
$("#green").trigger("click");
Here's a JSfiddle with an example.
I have an error layer that is presented on a form for an invalid/blank entries. When that error layer is presented, I want the current field to lose focus. In IE, I can't get this to work. The focus is always remaining in the field.
<!--Jquery function to override JS alert with DOM layer alert message-->
function customAlert(){
var args = arguments;
if(args.length > 1) {
// check that custom alert was called with at least two arguments
var msg = args[0];
$("li").removeClass("alertRed");
$("input").removeClass("CO_form_alert");
$("select").removeClass("CO_form_alert");
var div = $(".errorPopup");
div.css({"display":"block"});
if (div.length == 0) {
div = $("<div class='errorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg);
for(var i = 1; i < args.length; i++) {
var inputID = args[i];
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
$("input,select,radio,checkbox").focus(function(){
$(this).unbind('focus'); // remove this handler
$('.errorPopup').hide(); // hide error popup
});
}
}
}
I've tried ('body').focus(); and $("#"+inputID).focusout(); which also don't work.
I also tried:
div.css({"display":"block"});
$("input,select,radio,checkbox").blur();
and
$("input,select,radio,checkbox").blur(function(){
$(this).unbind('focus'); // remove this handler
$('.errorPopup').hide(); // hide error popup
});
but neither one works.
Use blur method.
$("input,select,radio,checkbox").blur();
Did you try
$("input,select,radio,checkbox").blur();
?
I am using jquery to keep the focus on a text box when you click on a specific div. It works well in Internet Explorer but not in Firefox. Any suggestions?
var clickedDiv = false;
$('input').blur(function() { if (clickedDiv) { $('input').focus(); } });
$('div').mousedown(function() { clickedDiv = true; })
.mouseup(function() { clickedDiv = false });
Point to note: the focus() method on a jquery object does not actually focus it: it just cases the focus handler to be invoked! to actually focus the item, you should do this:
var clickedDiv = false;
$('input').blur( function() {
if(clickeddiv) {
$('input').each(function(){this[0].focus()});
}
}
$('div').mousedown(function() { clickedDiv = true; })
.mouseup(function() { clickedDiv = false });
Note that I've used the focus() method on native DOM objects, not jquery objects.
This is a direct (brute force) change to your exact code. However, if I understand what you are trying to do correctly, you are trying to focus an input box when a particular div is clicked when that input is in focus.
Here's my take on how you would do it:
var inFocus = false;
$('#myinput').focus(function() { inFocus = true; })
.blur(function() { inFocus = false; });
$('#mydiv').mousedown(function() {
if( inFocus )
setTimeout( function(){ $('#myinput')[0].focus(); }, 100 );
}
Point to note: I've given a timeout to focussing the input in question, so that the input can actually go out of focus in the mean time. Otherwise we would be giving it focus just before it is about to lose it. As for the decision of 100 ms, its really a fluke here.
Cheers,
jrh
EDIT in response to #Jim's comment
The first method probably did not work because it was the wrong approach to start with.
As for the second question, we should use .focus() on the native DOM object and not on the jQuery wrapper around it because the native .focus() method causes the object to actually grab focus, while the jquery method just calls the event handler associated with the focus event.
So while the jquery method calls the focus event handler, the native method actually grants focus, hence causing the handler to be invoked. It is just unfortunate nomenclature that the name of this method overlaps.
I resolved it by simply replace on blur event by document.onclick and check clicked element if not input or div
var $con = null; //the input object
var $inp = null; // the div object
function bodyClick(eleId){
if (eleId == null || ($inp!= null && $con != null && eleId != $inp.attr('id') &&
eleId != $con.attr('id'))){
$con.hide();
}
}
function hideCon() {
if(clickedDiv){
$con.hide();
}
}
function getEl(){
var ev = arguments[0] || window.event,
origEl = ev.target || ev.srcElement;
eleId = origEl.id;
bodyClick(eleId);
}
document.onclick = getEl;
hope u find it useful