Trying to convert this old code to work with new jquery but I'm missing something.
Old Code - It uses Live() which is no longer supported.
$(document).ready(function(){
$("textarea").keydown(function(e) {
if(e.keyCode === 9) {
var start = this.selectionStart;
var end = this.selectionEnd;
var $this = $(this);
var value = $this.val();
$this.val(value.substring(0, start) + "\t" + value.substring(end));
this.selectionStart = this.selectionEnd = start + 1;
e.preventDefault();
}
});
//getting input from all three textareas
function getHTML() {
var html = $('#html').val();
return html;
}
function getCSS() {
var css = $('#css').val();
return css;
}
function getJS() {
var js = $('#js').val();
return js;
}
//put it in the preview area
$('textarea').live("keyup,"function(){
var targetIframe = $('preview')[0].contentWindow.document;
targetIframe.open();
targetIframe.close();
var html=getHTML();
var css ='<style>' + getCSS(); + '</style>';
var js ='<script>' + getJS(); + '</script>';
$('body',targetIframe).append(html);
$('head',targetIframe).append(css);
$('body',targetIframe).append(js);
});
});
With help from others I've gotten it here, but its still not functional.
$(document).ready(function(){
$("textarea").keydown(function(e) {
if(e.keyCode === 9) {
var start = this.selectionStart;
var end = this.selectionEnd;
var $this = $(this);
var value = $this.val();
$this.val(value.substring(0, start) + "\t" + value.substring(end));
this.selectionStart = this.selectionEnd = start + 1;
e.preventDefault();
}
});
//getting input from all three textareas
function getHTML() {
var html = $('#html').val();
return html;
}
function getCSS() {
var css = $('#css').val();
return css;
}
function getJS() {
var js = $('#js').val();
return js;
}
$(document).on("keyup", "textarea", function(){
var targetIframe = $('preview')[0].contentWindow.document;
targetIframe.open();
targetIframe.close();
var html=getHTML();
var css ='<style>' + getCSS(); + '</style>';
var js ='<script>' + getJS(); + '</script>';
$('body',targetIframe).append(html);
$('head',targetIframe).append(css);
$('body',targetIframe).append(js);
});
});
I know where the code is wrong, I am getting an error in the line that starts with 'var targetiFrame' I just don't know how to fix it. Please help?
Related
I am trying to make a click send function for my emoticon function but it is not working correctly.
I have created this demo from jsfiddle. In this demo you can se there are four textarea and smiley. When you click smiley then other alert (comments will be come here) changing to (Plese write your comment). What is the problem on there and what is the solution anyone can help me in this regard ?
JS
$('.sendcomment').bind('keydown', function (e) {
if (e.keyCode == 13) {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("Plese write your comment!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
}
});
/**/
$(document).ready(function () {
$('body').on("click", '.emo', function () {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
});
$('body').on('click', '.sm-sticker', function (event) {
event.preventDefault();
var theComment = $(this).parents('.container').find('.sendcomment');
var id = $(this).attr('id');
var sticker = $(this).attr('sticker');
var msg = jQuery.trim(theComment.val());
if (msg == '') {
var sp = '';
} else {
var sp = ' ';
}
theComment.val(jQuery.trim(msg + sp + sticker + sp));
var e = $.Event("keydown");
e.keyCode = 13; // # Some key code value
$('.sendcomment').trigger(e);
});
HTML
At 43 line $('.sendcomment').trigger(e); you trigger keydown event to all textareas. Change it to theComment.trigger(e)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a series of buttons loaded from a JSON, which in turn should disappear and append other buttons on click.
Like so (the first level of buttons is already on the page and reacting properly to other events like hover):
...
$(document).on('click', "#subcategoryButtons button", function () {
getTemplate('imgMenu.html');
var entryIndex = this.id[0];
var subentryIndex;
if (this.id[1] === '0')
{
subentryIndex = this.id.slice(-1);
}
else
{
subentryIndex = this.id.slice(-2);
}
var imgs = data.category[entryIndex].subcategory[subentryIndex].imgs;
$.each(imgs, function (imgIndex)
{
var imgName = data.category[entryIndex].subcategory[subentryIndex].imgs[imgIndex].imgName;
var imgId = data.category[entryIndex].subcategory[subentryIndex].imgs[imgIndex].imgId;
$('#imgButtons span').append('<button id="' + imgId + '">' + imgName + '</button>');
});
});
}
;
...
This is the content of the template being loaded:
<div id="imgSpace">
<aside id="overlayRight">
Right Overlay space
</aside>
<div id="overlayBottom">
Bottom Overlay
</div>
</div>
<nav id="imgButtons" class="resizable">
<span></span>
</nav>
Here's the getTemplate code:
function getTemplate(templateUrl)
{
$.get('templates/' + templateUrl, function (content)
{
if (templateUrl === 'leftMenu.html')
{
$('#leftMenu').html(content);
}
else
{
$('#main').html(content);
}
});
}
Even though it should append the buttons to the #imgButtons span, it seems as if it cannot select any of the elements in the template just loaded. If I try to append the buttons to another part of the page (say like the left menu, which is not recently loaded) or instead of getting a template I simply clear out the HTML in the main, the attachment works. So it appears that the issue is how to select elements that have been loaded. Any help would be greatly appreciated.
Thanks to everyone who pointed me in the right direction. In the end I didn't use Ajax but deferred.done like so:
$(document).on('click', "#subcategoryButtons button", function () {
var entryIndex = this.id[0];
var subentryIndex;
if (this.id[1] === '0') {
subentryIndex = this.id.slice(-1);
} else {
subentryIndex = this.id.slice(-2);
}
var imgs = data.category[entryIndex].subcategory[subentryIndex].imgs;
$('main').html('');
$.get("templates/imgMenu.html", function (content)
{
$('#main').html(content);
}).done(function () {
$.each(imgs, function (imgIndex) {
var imgName = data.category[entryIndex].subcategory[subentryIndex].imgs[imgIndex].imgName;
var imgId = data.category[entryIndex].subcategory[subentryIndex].imgs[imgIndex].imgId;
console.log(entryIndex);
$('#imgButtons span').append('<button id="' + imgId + '">' + imgName + '</button>');
});
});
});
}
;
You're using the wrong selector #imgButtons button should be #imgButtons span to select the span in #imgButtons
Also your template is loaded asynchronously so you'll have to wait until it is loaded (via a callback function) to manipulate it. something like
$(document).on('click', "#subcategoryButtons button", function () {
getTemplate('imgMenu.html', callback);
function callback(){
var entryIndex = this.id[0];
var subentryIndex;
if (this.id[1] === '0')
{
subentryIndex = this.id.slice(-1);
}
else
{
subentryIndex = this.id.slice(-2);
}
var imgs = data.category[entryIndex].subcategory[subentryIndex].imgs;
$.each(imgs, function (imgIndex)
{
var imgName = data.category[entryIndex].subcategory[subentryIndex].imgs[imgIndex].imgName;
var imgId = data.category[entryIndex].subcategory[subentryIndex].imgs[imgIndex].imgId;
$('#imgButtons span').append('<button id="' + imgId + '">' + imgName + '</button>');
});
}
});
...
function getTemplate(templateUrl, callback)
{
$.get('templates/' + templateUrl, function (content)
{
if (templateUrl === 'leftMenu.html')
{
$('#leftMenu').html(content);
}
else
{
$('#main').html(content);
}
callback();
});
}
let's make a bit modification on your code, use promises - the jqxhr object returned by the ajax method implements the promise interface, therefore you could make use of it.
function getTemplate(templateUrl)
{
return $.get('templates/' + templateUrl, function (content)
{
if (templateUrl === 'leftMenu.html')
{
$('#leftMenu').html(content);
}
else
{
$('#main').html(content);
}
});
}
use it in this way
$(document).on('click', "#subcategoryButtons button", function (e) {
getTemplate('imgMenu.html').then(function () {
var entryIndex = this.id[0];
var subentryIndex;
if (this.id[1] === '0') {
subentryIndex = this.id.slice(-1);
} else {
subentryIndex = this.id.slice(-2);
}
var imgs = data.category[entryIndex].subcategory[subentryIndex].imgs;
$.each(imgs, function (imgIndex) {
var imgName = data.category[entryIndex].subcategory[subentryIndex].imgs[imgIndex].imgName;
var imgId = data.category[entryIndex].subcategory[subentryIndex].imgs[imgIndex].imgId;
$('#imgButtons span').append('<button id="' + imgId + '">' + imgName + '</button>');
});
});
});
I'm using this code to debug...
$(document).ready(function() {
$('.slider').slider();
});
$.fn.slider = function() {
return this.each(function() {
var $el = $(this);
var dragging = false;
var startX = $el.offset().left;
var startL = 0;
$el.mousedown(function(ev) {
dragging = true;
startX = ev.clientX;
startL = $(this).css('left');
alert("class: "+ $el.className +" id: " + $el.id);
});
$(document).mousemove(function(ev) {
if (dragging) {
var newLeft = parseInt(startL) + (ev.clientX - startX);
$el.css('left', newLeft );
}
}).mouseup(function() {
dragging = false;
});
});
}
Note: alert("class: "+ $el.className +" id: " + $el.id);
It always returns "undefined" for $el.className and $el.id.
How can I get it to return the id and class of the element (div) that I've clicked on?
I've tried many variant of $el and .id, but nothing seems to work.
You're mixing jQuery and vanilla javascript properties. className is vanilla and $(this) makes a jQuery object.
Either change
$el.className
to
$el.attr('class')
or if you want to use className:
var $el = $(this);
to
var $el = this;
(although that would require changing other parts of code as well)
try like following:
$(function() {
$("div").click(function() {
var name = this.name;
var cls = this.className;
var id= this.id;
alert("Name: " + name + " / Class: " + cls + " / Id: " + id);
});
});
I have been using the HTML 5 placeholder and just realised that it does not work outside HTML5 devices. As you can see by the code below the placeholder is always in lowercase and the value is always in upper case.
#maphead input::-webkit-input-placeholder {
text-transform:lowercase;
}
#maphead input:-moz-placeholder {
text-transform:lowercase;
}
<input id="start" type="text" spellcheck="false" placeholder="enter your post code" style="text-transform:uppercase;" class="capital"/>
This is all fine except when dealing with non HTML 5 devices. For this I have employed a bastardised bit of javascript.
function activatePlaceholders() {
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
if (inputs[i].getAttribute("type") == "text") {
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0 || value == placeholder) {
inputs[i].value = placeholder;
inputs[i].onclick = function() {
if (this.value == this.getAttribute("placeholder")) {
this.value = "";
}
return false;
}
inputs[i].onblur = function() {
if (this.value.length < 1) {
this.value = this.getAttribute("placeholder");
$('.capital').each(function() {
var current = $(this).val();
var place = $(this).attr('placeholder');
if (current == place) {
$(this).css('text-transform','lowercase')
}
});
}
}
}
}
}
}
window.onload = function() {
activatePlaceholders();
}
Firstly this Javascript is rancid. There must be an easier JQuery way. Now although this above does work (reasonably) it does not respond to keeping the placeholder in lowercase and the value in uppercase since it sets the value with the placeholder.
I've set you all up with a nice Fiddle http://jsfiddle.net/Z9YLZ/1/
Try something like this:
$(function() {
$('input[type="text"]').each(function () {
$(this).focus(function () {
if ($(this).attr('value') === $(this).attr('placeholder')) {
$(this).css('text-transform','lowercase');
$(this).attr('value', '');
}
}).blur(function () {
if ($(this).attr('value') === '') {
$(this).css('text-transform','uppercase');
$(this).attr('value', $(this).attr('placeholder'));
}
}).blur();
});
});
Edit: Explicitly declare the text-transform to cascade properly.
Try this one, I'm using it for a while and it works perfectly:
(function($, undefined) {
var input = document.createElement('input');
if ('placeholder' in input) {
$.fn.hinttext = $.hinttext = $.noop;
$.hinttext.defaults = {};
delete input;
return;
}
delete input;
var boundTo = {},
expando = +new Date + Math.random() * 100000 << 1,
prefix = 'ht_',
dataName = 'hinttext';
$.fn.hinttext = function(options) {
if (options == 'refresh') {
return $(this).each(function() {
if ($(this).data(dataName) != null) {
focusout.call(this);
}
});
}
options = $.extend({}, $.hinttext.defaults, options);
if (!(options.inputClass in boundTo)) {
$('.' + options.inputClass)
.live('focusin click', function() {
$($(this).data(dataName)).hide();
})
.live('focusout', focusout);
boundTo[options.inputClass] = true;
}
return $(this).each(function(){
var input = $(this),
placeholder = input.attr('placeholder');
if (placeholder && input.data(dataName) === undefined) {
var input_id = input.attr('id'),
label_id = prefix + expando++;
if (!input_id) {
input.attr('id', input_id = prefix + expando++);
}
$('<label/>')
.hide()
.css('position', options.labelPosition)
.addClass(options.labelClass)
.text(placeholder)
.attr('for', input_id)
.attr('id', label_id)
.insertAfter(input);
input
.data(dataName, '#' + label_id)
.addClass(options.inputClass)
.change(function() {
focusout.call(this);
});
}
focusout.call(this);
});
};
$.hinttext = function(selector, options) {
if (typeof selector != 'string') {
options = selector;
selector = 'input[placeholder],textarea[placeholder]';
}
$(selector).hinttext(options);
return $;
};
$.hinttext.defaults = {
labelClass: 'placeholder',
inputClass: 'placeholder',
labelPosition: 'absolute'
};
function focusout() {
var input = $(this),
pos = input.position();
$(input.data(dataName)).css({
left: pos.left + 'px',
top: pos.top + 'px',
width: input.width() + 'px',
height: input.height() + 'px'
})
.text(input.attr('placeholder'))
[['show', 'hide'][!!input.val().length * 1]]();
}
$($.hinttext);
})(jQuery);
You just need to make sure to style label.placeholder with CSS to look the same as HTML5 placeholder text (color: #999)
Try this: http://jsfiddle.net/msm595/Z9YLZ/12/
Bit late but here's what I do. Store all the default values on page load and then clear value text ONLY when it's the default value that is clicked on. This prevents the JS clearing user entered text.
jQuery(document).ready(function($){
var x = 0; // count for array length
$("input.placeholder").each(function(){
x++; //incrementing array length
});
var _values = new Array(x); //create array to hold default values
x = 0; // reset counter to loop through array
$("input.placeholder").each(function(){ // for each input element
x++;
var default_value = $(this).val(); // get default value.
_values[x] = default_value; // create new array item with default value
});
var current_value; // create global current_value variable
$('input.placeholder').focus(function(){
current_value = $(this).val(); // set current value
var is_default = _values.indexOf(current_value); // is current value is also default value
if(is_default > -1){ //i.e false
$(this).val(''); // clear value
}
});
$('input.placeholder').focusout(function(){
if( $(this).val() == ''){ //if it is empty...
$(this).val(current_value); //re populate with global current value
}
});
});
Error message (Last line):
$("select").selectList is not a
function
Code:
(function( $ ){
$.fn.selectList = function(options) {
var settings = {
'buttonClass' : 'custom-select',
'buttonTextClass' : 'custom-select-status',
'buttonIconClass' : 'custom-select-button-icon',
'menuClass' : 'custom-select-menu',
'menuClassHidden' : 'custom-select-menu-hidden'
}
$('body').click(function() {
$('.' + settings.menuClass).each(function() {
$(this).addClass(settings.menuClassHidden);
})
});
return this.each(function() {
if (options) {
$.extend(settings, options);
}
var $this = $(this).hide(),
$menu = $('<ul></ul>').addClass(settings.menuClass)
.addClass(settings.menuClassHidden),
optionsTexts = new Array(),
currIdx;
$this.find('option').each(function(idx) {
var $opt = $(this);
if ($opt.is(':selected')) {
currIdx = idx;
}
optionsTexts[idx] = $opt.text();
})
for (var i = 0; i < optionsTexts.length; i++) {
var $item = $('<li></li>'),
$link = $('' + optionsTexts[i] + '');
if (i == currIdx) {
$item.addClass('selected');
}
$link.click(function() {
var linkIdx = $link.parent().parent().find('li').index($link.parent());
$this.find('option').eq(linkIdx).attr('selected', 'selected');
$menu.prev().find('.' + settings.buttonTextClass).text($link.text());
if ($menu.hasClass(settings.menuClassHidden)) {
$menu.removeClass(settings.menuClassHidden);
} else {
$menu.addClass(settings.menuClassHidden);
}
});
$item.append($link);
$menu.append($item);
}
$menu.insertBefore($this);
$('')
.html('<span class="'+ settings.buttonTextClass + '">'+ optionsTexts[currIdx] +'</span><span class="' + settings.buttonIconClass + '"></span>')
.addClass(settings.buttonClass)
.insertBefore($menu)
.click(function() {
$('.custom-select-menu').addClass(settings.menuClassHidden);
$menu.hasClass(settings.menuClassHidden)
? $menu.removeClass(settings.menuClassHidden)
: $menu.addClass(settings.menuClassHidden);
return false;
});
});
};
})(jQuery);
$(document).ready(function() {
if (! $('.section-admin').length > 0) {
$('select').selectList();
}
});
Could somebody help?
This works perfect.
See an working example here: Custom jQuery works
Please check if somewhere, somehow you're not initializing jQuery twice. See this answer: https://stackoverflow.com/a/33054683/1712145