mootools select box focus - select

I have a select box
<select>
<option value="0">0 mins</option>
<option value="1">1 mins</option>
<option value="2">2 mins</option>
</select>
and I want to fire an event when the visitor either clicks on a value or clicks anywhere else on the page -i.e loss of focus on the select box
I've fiddled about for four hours now with no joy. I'm now down to this:
var c = 0;
$("selectTime").addEvent('click', function() {
if (c++ % 2 == 1) {
console.log(c);
//$(this).blur();
}
});
$('selectTime').click(function() {
if ($('select').is(':blur')) {
c = 1;
} else {
c = 0;
}
});
any ideas?
thanks

The mootools syntax for adding multiple events to same element is:
$('myElementID').addEvents({
blur: function(){
alert('blur');
},
click: function(){
alert('click');
}
});
Example with you code
You could though use just the change event, which fires when the element is changed. Like:
$('myElement').addEvent('change', function(){
alert('Select changed');
});
Example
Note that part of your code is using jQuery syntax, part is using MooTools syntax.

Related

vuejs2 draggable and sortable list

I have a list which is sortable with drag and drop. And it works
https://codepen.io/destroy90210/pen/rGEodB
Now I wanted to include the feature to sort the list by name, date and position.
So if i see the list sorted by name or date i block the drag an drop functionality. Only if position is selected, from the dropdown, the items are dragable, but now my drag and drop doesn't work any more. The items jump back to the old position...
https://codepen.io/destroy90210/pen/yzdQxK
<div id="main">
<select class="dd" v-model="orderBy" #change="sortedData">
<option value='created'>created</option>
<option value='abc'>Abc</option>
<option value='position'>Position</option>
</select>
<draggable :list="data" class="dragArea" #change="changeOrder" :options="{draggable:'.card--dragable'}">
<div :class="{'card--dragable': isDragable}" class="card" v-for="item in sortedData"><span class="card__label">{{item.name}}</span></div>
</draggable>
</div>
new Vue({
el: "#main",
data: {
data: data,
orderBy: 'position',
isDragable: true,
},
computed:{
sortedData(){
this.isDragable = false;
if (this.orderBy === 'abc') {
return this.data.sort((a, b) => { return a.name.localeCompare(b.name); });
} else if (this.orderBy === 'created') {
return this.data.sort((a, b) => { return a.id > b.id; });
}
this.isDragable = true;
return this.data.sort((a, b) => { return a.position > b.position; });
},
},
methods:{
changeOrder(e){
const oldIndex = e.moved.oldIndex;
const newIndex = e.moved.newIndex;
let i = Math.min(oldIndex, newIndex);
const max = Math.max(oldIndex, newIndex) + 1;
for (i; i < max; i += 1) {
this.data[i].position = i;
}
}
}
});
Fix: https://codepen.io/destroy90210/pen/jGgNBN
sortedData() is a computed element in your codepen, this means it will execute when its dependencies update (in your case when changeOrder() gets executed on a drag/drop action).
Use a method instead so it only executes when your select is updated by the following change event:
<select class="dd" v-model="orderBy" #change="sortedData">
This means we can fix the issue by moving sortedData() from computed to methods.
Now it wont update on a drop anymore.
Documentation about computed vs methods.

Wordpress shortcode preview in tinyMCE

I've written a shortcode and its functioning like it should. Now the hard part:
I would like to show the user a preview already in the tinyMCE editor. Loading CSS in the editor is not a problem for me, but i would love to know if it is possible to already process the shortcode within TinyMCE.
Thanks!
Let the code talk:
I'll put a code to add a visual icon for highlight content word(s) shortcode, and you can then implement any other shortcode you want with the same logic,
class spot_shortcodes {
function spot_shortcodes()
{
add_action('init', array(&$this, 'init'));
}
function init(){
// Enable shortcodes in text widgets
add_filter( 'widget_text', 'do_shortcode' );
// Fix for large posts, http://core.trac.wordpress.org/ticket/8553
#ini_set( 'pcre.backtrack_limit', 500000 );
// init process for button control
add_filter( 'tiny_mce_version', 'my_refresh_mce');
// Add only in Rich Editor mode
if ( get_user_option('rich_editing') == 'true') {
add_filter('mce_buttons_3', array(&$this, 'register_highlight_button'));
}
}
// Add your button plugin js code to tinyMCE
// codex: wp_register_script( $handle, $src, $deps, $ver, $in_footer );
wp_register_script( 'effects-highlight', SPOT_SHORTCODES_URL . '/js/jquery.effects.highlight.js', false ,SPOT_SHORTCODES_URL, true );
function add_youtube_button() {
// Don't bother doing this stuff if the current user lacks permissions
if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') )
return;
// Add only in Rich Editor mode
if ( get_user_option('rich_editing') == 'true') {
add_filter("mce_external_plugins", array(&$this, "add_youtube_tinymce_plugin"));
add_filter('mce_buttons', array(&$this, 'register_highlight_button'));
}
}
// function to register you button to tinyMCE dashboard
function register_highlight_button($buttons) {
array_push($buttons, "|", 'highlight_button');
return $buttons;
}
function add_youtube_tinymce_plugin($plugin_array) {
// your icon image(highlight.png) which will be displayed in the tinyMCE dashboard
$plugin_array['highlight'] = SPOT_TINYMCE_URL . '/icons-lib-custom.js';
return $plugin_array;
}
} // class end
// Finally make an object from your button
$spot_shortcodes = new spot_shortcodes();
Our js code for the highlight button option
make an dot js file put the followin code in it and put it in the tinyMCE plugin directory
// dont forget to change the paths
tinymce.create('tinymce.plugins.highlight', {
// creates control instances based on the control's id.
// our button's id is "highlight_button"
createControl : function(id, controlManageradel) {
if (id == 'highlight_button') {
// creates the button
var button = controlManageradel.createButton('highlight', {
title : 'Add a Hightlight Text', // title of the button
image :spotShortcodes.plugin_folder +"/tinymce/images/highlight.png", // path to the button's image
onclick : function() {
// triggers the thickhighlight
var width = jQuery(window).width(), H = jQuery(window).height(), W = ( 720 < width ) ? 720 : width;
W = W - 80;
H = H - 84;
tb_show( 'Insert text box shortcode', '#TB_inline?width=' + W + '&height=' + H + '&inlineId=highlight-form' );
}
});
return button;
}
return null;
}
});
// registers the plugin. DON'T MISS THIS STEP!!!
tinymce.PluginManager.add('highlight', tinymce.plugins.highlight);
// executes this when the DOM is ready
jQuery(function(){
// creates a form to be displayed everytime the button is clicked
// you should achieve this using AJAX instead of direct html code like this
var form = jQuery('<div id="highlight-form"><table id="highlight-table" class="form-table" style="text-align: left">\
\
\
<tr>\
<th><label class="title" for="highlight-bg">Highlight color</label></th>\
<td><select name="bg" id="highlight-bg">\
<option value="#f02d33">Red</option>\
<option value="#b6bbbd">Grey</option>\
<option value="#3e3c3c">Darkgrey</option>\
<option value="#99cc33">Lightgreen</option>\
<option value="#6c8c2d">Darkgreen</option>\
<option value="#0f5ac6">Blue</option>\
<option value="#3cbcf7">Cyan</option>\
<option value="#9219f8">Purple</option>\
<option value="#fcc016">Yellow</option>\
<option value="#f65e0e">Orange</option>\
</select><br />\
<div class="info"><small>Select box type.</small></div></td>\
</tr>\
<tr>\
<th><label class="title" for="highlight-contet">Conent</label></th>\
<td><textarea rows="7"\ cols="45"name="content" id="highlight-content">hightlight text</textarea>\
<br />\
<div><small>this text displayed in box.</small></div></td>\
</tr>\
</table>\
<p class="submit">\
<input type="button" id="highlight-submit" class="button-primary" value="Insert shortcode" name="submit" style=" margin: 10px 150px 50px; float:left;"/>\
</p>\
</div>');
var table = form.find('table');
form.appendTo('body').hide();
// handles the click event of the submit button
form.find('#highlight-submit').click(function(){
// defines the options and their default values
// again, this is not the most elegant way to do this
// but well, this gets the job done nonetheless
var options = {
'bg' : '#f02d33',
'content' : 'hightlight text',
};
var shortcode = '[highlight ';
for( var index in options) {
var value = table.find('#highlight-' + index).val();
// attaches the attribute to the shortcode only if it's different from the default value
if ( value !== options[index] & index !== 'content')
shortcode += ' ' + index + '="' + value + '"';
}
shortcode += ']'+ value + '[/highlight]'
// inserts the shortcode into the active editor
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, shortcode);
// closes Thickhighlight
tb_remove();
});
});
I hope this help, give me you feedback if you want any more explanation, thanks.

Google Autocomplete - enter to select

I have Google Autocomplete set up for a text field of an HTML form, and it's working perfectly.
However, when the list of suggestions appear, and you use the arrows to scroll and select using enter, it submits the form, though there are still boxes to fill in. If you click to select a suggestion it works fine, but pressing enter submits.
How can I control this? How can I stop enter from submitting the form, and instead be the selection of a suggestion from autocomplete?
Thanks!
{S}
You can use preventDefault to stop the form being submitted when enter is hit, I used something like this:
var input = document.getElementById('inputId');
google.maps.event.addDomListener(input, 'keydown', function(event) {
if (event.keyCode === 13) {
event.preventDefault();
}
});
Using the Google events handling seems like the proper solution but it's not working for me. This jQuery solution is working for me:
$('#inputId').keydown(function (e) {
if (e.which == 13 && $('.pac-container:visible').length) return false;
});
.pac-container is the div that holds the Autocomplete matches. The idea is that when the matches are visible, the Enter key will just choose the active match. But when the matches are hidden (i.e. a place has been chosen) it will submit the form.
I've amalgamated the first two answers from #sren and #mmalone to produce this:
var input= document.getElementById('inputId');
google.maps.event.addDomListener(input, 'keydown', function(e) {
if (e.keyCode == 13 && $('.pac-container:visible').length) {
e.preventDefault();
}
});
works perfectly on the page. prevents the form from being submitted when the suggestion container (.pac-container) is visible. So now, an option from the autocomplete dropdown is selected when the users presses the enter key, and they have to press it again to submit the form.
My main reason for using this workaround is because I found that if the form is sent as soon as an option is selected, via the enter key, the latitude and longitude values were not being passed fast enough into their hidden form elements.
All credit to the original answers.
This one worked for me:
google.maps.event.addDomListener(input, 'keydown', e => {
// If it's Enter
if (e.keyCode === 13) {
// Select all Google's dropdown DOM nodes (can be multiple)
const googleDOMNodes = document.getElementsByClassName('pac-container');
// Check if any of them are visible (using ES6 here for conciseness)
const googleDOMNodeIsVisible = (
Array.from(googleDOMNodes).some(node => node.offsetParent !== null)
);
// If one is visible - preventDefault
if (googleDOMNodeIsVisible) e.preventDefault();
}
});
Can be easily converted from ES6 to any browser-compatible code.
The problem I had with #sren's answer was that it blocks the submit event always. I liked #mmalone's answer but it behaved randomly, as in sometimes when I hit ENTER to select the location, the handler ran after the container is hidden. So, here's what I ended up doing
var location_being_changed,
input = document.getElementById("js-my-input"),
autocomplete = new google.maps.places.Autocomplete(input),
onPlaceChange = function () {
location_being_changed = false;
};
google.maps.event.addListener( this.autocomplete,
'place_changed',
onPlaceChange );
google.maps.event.addDomListener(input, 'keydown', function (e) {
if (e.keyCode === 13) {
if (location_being_changed) {
e.preventDefault();
e.stopPropagation();
}
} else {
// means the user is probably typing
location_being_changed = true;
}
});
// Form Submit Handler
$('.js-my-form').on('submit', function (e) {
e.preventDefault();
$('.js-display').text("Yay form got submitted");
});
<p class="js-display"></p>
<form class="js-my-form">
<input type="text" id="js-my-input" />
<button type="submit">Submit</button>
</form>
<!-- External Libraries -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
The flag ensures that if the location is being changed & user hits enter, the event is blocked. Eventually the flag is set to false by google map's place_changed event, which then allows the form to be submitted on hitting the enter key.
Here's a simple code that worked well for me (uses no jquery).
const googleAutcompleteField = this.renderer.selectRootElement(this.elem.nativeElement);
this.selectOnEnter(googleAutcompleteField);
This piece of code, to follow the code above, is used to implement google maps autocomplete (with or without the Enter key functionality sought in this question):
this.autocomplete = new google.maps.places.Autocomplete(googleAutcompleteField, this.googleMapsOptions);
this.autocomplete.setFields(['address_component', 'formatted_address', 'geometry']);
this.autocomplete.addListener('place_changed', () => {
this.zone.run(() => {
this.googleMapsData.emit([this.autocomplete.getPlace()]);
})
})
selectOnEnter (called above in the first piece of code) defined:
selectOnEnter(inputField) {
inputField.addEventListener("keydown", (event) => {
const selectedItem = document.getElementsByClassName('pac-item-selected');
if (event.key == "Enter" && selectedItem.length != 0) {
event.preventDefault();
}
})
}
This code makes the google maps autocomplete field select whichever item user selects with the down arrow keypress. Once user selects an option with a press of the Enter key, nothing happens. User has to press Enter again to trigger onSubmit() or other command
You can do it in vanilla :
element.addEventListener('keydown', function(e) {
const gPlaceChoices = document.querySelector('.pac-container')
// No choices element ?
if (null === gPlaceChoices) {
return
}
// Get choices visivility
let visibility = window.getComputedStyle(gPlaceChoices).display
// In this case, enter key will do nothing
if ('none' !== visibility && e.keyCode === 13) {
e.preventDefault();
}
})
I tweaked Alex's code, because it broke in the browser. This works perfect for me:
google.maps.event.addDomListener(
document.getElementById('YOUR_ELEMENT_ID'),
'keydown',
function(e) {
// If it's Enter
if (e.keyCode === 13) {
// Select all Google's dropdown DOM nodes (can be multiple)
const googleDOMNodes = document.getElementsByClassName('pac-container');
//If multiple nodes, prevent form submit.
if (googleDOMNodes.length > 0){
e.preventDefault();
}
//Remove Google's drop down elements, so that future form submit requests work.
removeElementsByClass('pac-container');
}
}
);
function removeElementsByClass(className){
var elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
}
I've tried the above short answers but they didn't work for me, and the long answers I didn't want to try them, so I've created the following code which worked pretty well for me. See Demo
Suppose this is your form:
<form action="" method="">
<input type="text" name="place" id="google-places-searchbox" placeholder="Enter place name"><br><br>
<input type="text" name="field-1" placeholder="Field 1"><br><br>
<input type="text" name="field-2" placeholder="Field 2"><br><br>
<button type="submit">Submit</button>
</form>
Then the following javascript code will solve the problem:
var placesSearchbox = $("#google-places-searchbox");
placesSearchbox.on("focus blur", function() {
$(this).closest("form").toggleClass('prevent_submit');
});
placesSearchbox.closest("form").on("submit", function(e) {
if (placesSearchbox.closest("form").hasClass('prevent_submit')) {
e.preventDefault();
return false;
}
});
And here is how the full code looks like in the HTML page (Note that you need to replace the YOUR_API_KEY with your google api key):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Prevent form submission when choosing a place from google places autocomplete searchbox</title>
</head>
<body>
<form action="" method="">
<input type="text" name="place" id="google-places-searchbox" placeholder="Enter place name"><br><br>
<input type="text" name="field-1" placeholder="Field 1"><br><br>
<input type="text" name="field-2" placeholder="Field 2"><br><br>
<button type="submit">Submit</button>
</form>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Google Maps -->
<!-- Note that you need to replace the next YOUR_API_KEY with your api key -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"
async defer></script>
<script>
var input = document.getElementById("google-places-searchbox");
var searchBox = new google.maps.places.SearchBox(input);
var placesSearchbox = $("#google-places-searchbox");
placesSearchbox.on("focus blur", function() {
$(this).closest("form").toggleClass('prevent_submit');
});
placesSearchbox.closest("form").on("submit", function(e) {
if (placesSearchbox.closest("form").hasClass('prevent_submit')) {
e.preventDefault();
return false;
}
});
</script>
</body>
</html>
$("#myinput").on("keydown", function(e) {
if (e.which == 13) {
if($(".pac-item").length>0)
{
$(".pac-item-selected").trigger("click");
}
}
Use $('.pac-item:first').trigger('click'); if you want to select first result

How to bind event to multiple selectmenu change in jquerymobile

I want to refresh my page when I finish choosing the selects in jquerymobile.Now Im using the onchange attribute in tag.here's my code.
<div data-role="fieldcontain" style = "background-color:white;border-bottom:1px solid #ccc">
<label for="select-choice-1" class="select">select specity:</label>
<select name="select-choice-1" id="select-choice-1" data-native-menu = false multiple=true onchange = "selectChange()"></select>
</div>
$("#select-choice-1").empty();
for (var i = 0; i < item.tagClassList.length; i++) {
if (item.tagClassList[i].isSelected) {
$("#select-choice-1").append("<option value="+item.tagClassList[i].id+"checked = true>"+item.tagClassList[i].className+"</option>");
} else {
$("#select-choice-1").append("<option value="+item.tagClassList[i].id+">"+item.tagClassList[i].className+"</option>");
}
if (i == item.tagClassList.length-1) {
$("#select-choice-1").selectmenu("refresh");
};
};
But the selectmenu() event fires whenever select is selected or selected is cancelled.How can I get the event fires when the selectmenu is closed
try binding to blur() like so
$('document').on('blur', '#select-choice-1', function(){
//run your check here
});
this also takes care of older versions of ios which seem to not fire change events on multiple selects.

How to bind multiple pair of selector:event in jQuery ON method

I m using jQuery 1.7+ latest .on method, but failed to implements, please help me.
working Fiddle.
basically here is my
HTML
<ul id="sortByRight" >
<li id="1">List</li>
<li id="2">Photo</li>
<li id="3">Map</li>
</ul>
<select name="sort" id="sort" >
<option value="1">Recommended</option>
<option value="2">Price: low to high</option>
<option value="3">Price: high to low </option>
<option value="4">Newest</option>
</select>
jQuery code
$(document).on('change click', 'ul#sortByRight,select#sort', function() {
selectedOption = $('select#sort').val();
whatToShow = $(this).attr('id');
alert('selectedOption:'+selectedOption+'whatToShow:'+whatToShow);
}
);
now I havebelow problems/queries.
can we bind one event with one selector i.e. above function should be called
EITHER on change of selectbox OR on click of ul.
how to set data argument in .on method. I have tried like below
$(document).on('change click', 'ul#sortByRight,select#sort',
{ selectedOption : $('select#sort').val(), whatToShow : $(this).attr('id') } ,
function(){console.log('selectedOption:'+selectedOption+'whatToShow:'+whatToShow);}
);
but get an error that selectedOption is not defined.
can we write something like this $(this, li); because I need the id of li not the id of selectbox.
if there is any other optimized solution ( using function like live or bind ), then please tell me.
Thanks A Lot.
I'm not 100% clear on what you actually want to do, but one thing doesn't make much sense. You want to send the ID of the LI when the select box is changed. Which LI? The last LI clicked? You need to store the state of the active LI so that you can send it in the ajax request if the select box is changed.
Perhaps something like this:
$('select#sort').change(function() {
processAjax();
});
$('ul#sortByRight > li > a').click(function() {
$(this).closest('ul').find('li').removeClass('active');
$(this).closest('li').addClass('active');
processAjax();
});
function processAjax() {
selectedOption = $('select#sort').val();
whatToShow = $('ul#sortByRight').find('.active').attr('id');
alert('selectedOption:' + selectedOption + 'whatToShow:' + whatToShow);
}
or check out the jsFiddle