jQuery not behaving as expected in reference to clicks - javascript

I have an element that I grab the content of and swap for an input, I then want to user to be able to click on the input (to enter text as normal), but if they click anywhere else to swap it back to the text.
However the click event seems to fire even the very first time the user clicks anywhere on the page. My code is below, have I misunderstood something?
$(document).ready(function(){
$("#thingy").css('cursor', 'pointer');
$("#thingy").one("click", function() {
var element = $(this);
element.css('cursor', 'auto');
element.css('display', 'inline-block');
element.fadeOut(100, function(){element.html('<input type="text" size="25" value="' + element.text() + '" style="width:' + element.width() + 'px;height:' + element.height() + 'px;border:none;padding:0px;margin:0px;">')}).fadeIn(100);
$("#thingy").click(function() {
return false;
});
$(document).click(function() {
alert("You clicked off the text-box");
element.html(element.children('input:text').val());
});
});
});

The reason it alerts even the first time is the first click handler (the .one() doesn't itself return false; or .stopPropgaton(), like this:
$(document).ready(function(){
$("#thingy").css('cursor', 'pointer');
$("#thingy").one("click", function() {
var element = $(this);
element.css('cursor', 'auto');
element.css('display', 'inline-block');
element.fadeOut(100, function(){element.html('<input type="text" size="25" value="' + element.text() + '" style="width:' + element.width() + 'px;height:' + element.height() + 'px;border:none;padding:0px;margin:0px;">')}).fadeIn(100);
$("#thingy").click(function() {
return false;
});
$(document).click(function() {
alert("You clicked off the text-box");
element.html(element.children('input:text').val());
});
return false;
});
}); ​
You can test it out here.
A better approach would be to use the blur event instead, replacing this:
$("#thingy").click(function() {
return false;
});
$(document).click(function() {
alert("You clicked off the text-box");
element.html(element.children('input:text').val());
});
return false;
With this:
$(element).delegate("input", "blur", function() {
element.html(element.children('input:text').val());
});
You can try that version here.

Related

Jquery previous .html() element still showing when new element clicked

I have to write code which finds all anchors and attaches a function that displays a popup of the elements text. My code is probably a mess, but I was able to get it working however the issue I have now is:
If I click link 1, then link 2, then click link 1 again, it displays link 2's text however if i click it again it displays the correct text.
I am not sure exactly how to rewrite or go about fixing this code to properly display the element which is clicked, text all the time.
here is a jsfiddle example: http://jsfiddle.net/2aLfL/1/
$(document).ready(function() {
function deselect(e) {
$('.pop').slideFadeToggle(function() {
e.removeClass('selected');
});
}
$(function() {
$('a').click(function(){
if($(this).hasClass('selected')){
deselect($(this));
} else {
$(this).addClass('selected');
$('.pop').slideFadeToggle();
var elText = $(this).text();
$('#elPop').html("<p>" + "<br><br>" + "You just clicked: <br><b>" + elText + "</b><br><br><br>" + "Click anywhere to Close" + "</p>");
console.log(this);
$("#closeWin").click(function () {
$('.anchorpop').hide();
});
}
return false;
});
});
$(function close(){
$(document).click(function(){
$('.anchorpop').hide();
});
});
$.fn.slideFadeToggle = function(easing, callback) {
return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};
});
You're binding the following click handler
$("#closeWin").click(function () {
$('.anchorpop').hide();
});
inside <a> click handler so whenever a link is clicked, multiple handlers are being added.
You can avoid many unnecessary code using toggleClass() method.
You can also bind same event handlers to multiple elements by passing additional selectors.
after all your code boils down to
$(function () {
$('a').click(function () {
var htmlString = "<p>" + "<br><br>" + "You just clicked: <br><b>" + $(this).text() + "</b><br><br><br>" + "Click anywhere to Close" + "</p>"
$('.pop').html(htmlString).slideFadeToggle(function () {
$(this).toggleClass('selected');
});
return false;
});
$("#closeWin, .anchorpop").click(function () {
$('.anchorpop').hide();
});
});
and the custome slideFadeToggle function.
Updated Fiddle

Javascript/jQuery: input 'blur' prevents 'click' being fired

jsBin:
http://jsbin.com/eyARuHI/2/edit?html,css,js,output
Code:
$('#in').on('blur', function(event) {
alert('input: ' + event.type);
});
$('#button').on('click', function(event) {
alert('button: ' + event.type);
});
HTML:
<input id='in' type='text'>
<div id='button'></div>
Issue:
If focus the input and then click on button - click will never be fired.
How to properly handle click event in such cases?
As suggested by #RGraham try following JS. You will be able see that button event get fired every time when you click on it.
$('#in').on('blur', function(event) {
console.log('input: ' + event.type);
});
$('#button').on('click', function(event) {
console.log('button: ' + event.type);
});
you will need stop bubbling events. Try this
$('#button').on('click', function(event) {
alert('button: ' + event.type);
return false;
});
$('#in').on('blur', function(event) {
alert('input: ' + event.type);
});

jQuery Sortable Issue On/Off Checking

I've broken it again, and no idea how.
I have a CodePen of my recent activities.
What I've been trying to implement is a sortable function that checks first if there's only one #p_scents. If there is, it shouldn't be sortable (ie the .icon-sort shouldn't be activated). However if there is more than one, it should be sortable.
The problem I ran into however is after all but one has been deleted, the sortable functionality is still activated as it doesn't RE-check for how many #p_scents exist.
How can I fix this?
FYI somehow I broke the sortable functionality now o_O
$(function () {
var i = 1;
//ADD ROW
$('body').on('click', '.addPTbutton', function () {
var box = '<table class="manage-pt" id="' + i + '"><tr class="pt-entry"><td class="pt-toggle-group"><input class="pt-button togPTbutton" id="0" type="button" value="▾"><input class="pt-button addPTbutton" id="0" type="button" value="+"><input class="pt-button delPTbutton" id="' + i + '" type="button" value="-"></td><td class="pt-values"><div><input class="vendor" placeholder="*Vendor Name" type="text"><i class="icon-sort"></i><i class="icon-lock"></i></div><div><textarea class="ptCode" name="ptCode" placeholder="*Pixel Tag Code"></textarea></div><div class="page-select"><select><option value="AllPages">All Pages</option><option value="HomePage">HomePage</option><option value="VehicleDetailsPage">VehicleDetailsPage</option><option value="VehicleSearchResults">VehicleSearchResults</option><option value="ContactUsForm">ContactUsForm </option></select></div><div class="area-checkboxes"><p class="wheretosave">*Where?</p><input name="head" type="checkbox"><label for="head">Head</label><input name="body" type="checkbox"><label for="body">Body</label></div><hr/></td></tr></table>';
i++;
$("#p_scents").append(box);
return false;
});
//DELETE ROW
$('body').on('click', '.delPTbutton', function () {
var boxnum = $(".manage-pt").length;
if (boxnum <= '1') {
alert('Cannot Delete Last Remaining Row');
} else {
$(this).parents().eq(3).remove();
}
return false;
});
//TOGGLE BUTTON
$('body').on('click', '.togPTbutton', function () {
var hiddenarea = $(this).parent().next().children().next();
if ($(hiddenarea).is(':hidden')) {
//PT-VALUES OPENED
$(this).val('▾');
$(this).parent().next().children(0).children(0).attr('readonly', false);
} else {
//PT-VALUES HIDDEN
$(this).val('▸');
$(this).parent().next().children(0).children(0).attr('readonly', true);
}
//TOGGLE VISIBILITY OF HIDDEN AREA
hiddenarea.toggle();
});
//CHECKS FOR MORE THAN ONE 1 MANAGE-PT BEFORE ENABLES SORTABLE
$('body').on('click', '.icon-sort', function () {
if ($(".manage-pt").size() > 1) {
$('#p_scents').sortable({
disabled: false,
placeHolder: '.placeHolderHighlight',
handle: '.icon-sort',
});
} else $('#p_scents').sortable({
disabled: true,
});
});
//CHECK TO MAKE SURE ONLY ONE CHECKBOX IS SELECTED
var $onlyOne = $('.onlyOne');
$onlyOne.click(function () {
$onlyOne.filter(':checked').not(this).removeAttr('checked');
});
//LOCK BUTTON ON/OFF LOCKS FORM
$('body').on('click', '.icon-lock', function () {
$(this).toggleClass('locked');
var lockedarea = $(this).parents(0).eq(2);
$(lockedarea).find('input[type=text],input[type=checkbox],textarea,select').prop('disabled', function (_, val) {
return !val;
});
});
});
Your problem is here:
//CHECKS FOR MORE THAN ONE 1 MANAGE-PT BEFORE ENABLES SORTABLE
$('body').on('click', '.icon-sort', function () {...});
When make click on element ".icon-sort" is still sortable. You must use an action that makes the check before sort action begins: like mouseenter.
Here a jsfiddle

Syntax error with some JS/jquery code regarding });

I'm getting an error on some JS code for a content window I'm trying to create. I'm getting told that }); shouldn't be where it is, but I can't understand what the problem is. Am I using terms from an outdated jquery?
jQuery(document).ready(function($) {
$('.contentwindow_trigger').click(function(e) {
e.preventDefault();
var image_href = $(this).attr("href");
if ($('#contentwindow').length > 0) {
$('#content').html('<img src="' + image_href + '" />');
$('#contentwindow').show();
}
else {
var contentwindow =
'<div id="contentwindow">' +
'<p>Click to close</p>' +
'<section id="content">' +
'<img src="#" />' +
'</section>' +
'</div>';
$('body').append(contentwindow);
}
}); //HERE
$('#contentwindow').on('click', function() {
$('#contentwindow').hide();
});
});
The fault is where it says HERE, any help would be appreciated.
Thanks!
Use this sript:
jQuery(document).ready(function() {
$('.contentwindow_trigger').click(function(e) {
e.preventDefault();
var image_href = $(this).attr("href");
if ($('#contentwindow').length > 0) {
$('#content').html('<img src="' + image_href + '" />');
$('#contentwindow').show();
}
else {
var contentwindow =
'<div id="contentwindow">' +
'<p>Click to close</p>' +
'<section id="content">' +
'<img src="#" />' +
'</section>' +
'</div>';
$('body').append(contentwindow);
}
}); //HERE
$('#contentwindow').on('click', function() {
$('#contentwindow').hide();
});
});
remove the $ from this line your code
function($) {
to
function() {
/
jQuery(document).ready(function() {
$('.contentwindow_trigger').click(function(e) {
// Click event code
});
$('#contentwindow').on('click', function() {
$('#contentwindow').hide();
});
});
One more change required which does not affect the Syntax error in the page is that I see that you are dynamically adding an element and associating a click event to it .
You need to delegate the event for such case and the Event might not work
$('body').on('click','#contentwindow' , function() {
$('#contentwindow').hide();
});
Not sure what the syntax error you're seeing is, but it seems to work fine in this jsfiddle:
http://jsfiddle.net/xV58c/
One change I made there that may help you. Instead of:
$('#contentwindow').on('click', function() {
$('#contentwindow').hide();
});
I did:
$('body').on('click', '#contentwindow', function() {
$('#contentwindow').hide();
});
which uses the "on" method in a way that allows the containing element ("body" in this case) to deal with events on elements below, even elements generated that way that #contentwindow is.
Hope this helps.

jquery select any dom element on page

Does anyone know how to select any element (possibly on click) on page like body is selected, div is selected, div#foo etc... so i can place it to some variable and edit it later on.
i've tried
$("*", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
alert("Clicked on - " + domEl.tagName);
});
but it's not working for all elements
You want to get the target property of the event:
$(document).click(function(e) {
e.stopPropagation();
var domEl = e.target; // or $(e.target) to jQuerytize it
alert("Clicked on - " + domEl.tagName);
});
See: http://www.quirksmode.org/js/events_properties.html
Demo: http://jsfiddle.net/karim79/dyHEA/
Try this.
$(function(){
$("*").click(function () {
console.log($(this));
return false;
}
);
});

Categories