Off click of focused div not activating on jQuery function - javascript

Here is my HTML
$html .= " <td><div class='edit_course' data-id='{$id}' data-type='_title' contenteditable='true'>{$obj->title}</div></td>";
Here is my jQuery:
var selector = 'div[contenteditable="true"]';
// initialize the "save" function
$(selector).focus(function(e) {
content_holder = $(this);
content = content_holder.html();
var id = $(this).data('id');
var type = $(this).data('type');
alert( id + type)
// one click outside the editable area saves the content
$('body').one('click', function(e) {
// but not if the content didn't change
if ($(e.target).is(selector) || content == content_holder.html()) {
return;
}
// Edited out AJAX call
});
});
The problem is, when I click on the div, the alert below triggers. When I click outside of the div (after the edit has been made), nothing happens. Can anyone see what is happening?
First click let's user edit content in div. The first click outside, should make ajax call to save.
EDIT: From recommendation below.
Here is new code this works perfectly except it calls the DB every time, all I need is a check to do that only if data is different and I think I got it from there.
Edit2: Final Code
var original_value = '';
$(".edit_course").focus(function(e) {
original_value = $(this).html();
});
// initialize the "save" function
$(".edit_course").blur(function(e) {
var content = $(this).html();
var id = $(this).data('id');
var type = $(this).data('type');
if (content !== original_value) {
// Ajax edited out
}
});

You're not using one() correctly. What you should do is run the AJAX when focus is taken away from the div. Using blur() would probably be your best bet here.
$('body').blur(function(e) {
// your code here...
});

Related

preventDefault to stop refresh on anchor tag click

I have below line of code which simply places a link on the parent page:
<caps:msg textId="createNews"/>
Onclick of the above link 2 functions are getting called:
###func1():
var timestamp;
function func1() {
timestamp = +new Date();
return false;
}
###func2():
function func2(param1,param2,param3,param4){
var win;
var location = window.location.href; // location A
var encodeStringVar = encodeString(param3);
win = window.open(param1+'/struts1.action?param2='+param2+'&param3='+ escape(encodeStringVar) +'#'+param4,target='t1','toolbar=no,scrollbars=yes,menubar=no,location=no,width=990,height=630, top=100, left=100');
window.location.href = location; // location A
return win;
}
On click of link on parent page, a popup opens by calling struts action, and it works just fine. Only problem is when the link on parent page is clicked, it refreshes the parent page. I don't want it to refresh and I tried adding return false in the link and Javascript void() function, Also I tried by adding an event listener for click event on this link as below:
$(document).ready(function() {
$("#createNewsLink").click(function(event) {
//return false;
event.preventDefault();
})
})
and below:
$(document).ready(function() {
document.getElementById("createNewsLink").addEventListener("click", function(event) {
event.preventDefault();
});
})
But none of these did the trick, can someone please point out the mistake in my code?
Could you consider to try :
(function(){
var linkElement = document.querySelector('#createNewsLink');
linkElement.addEventListener('click',function(e) {
var param1 = e.target.getAttribute('attr-param1');
var param2 = e.target.getAttribute('attr-param2');
console.log(param1,param2);
// Do what ever you want here.
e.preventDefault();
});
})();
Click me
Here i avoid any Event binding from html, and centralize all traitment / binding in one place. Then i point one way to find back mandatory params for your traitment.

How to show the result of this jQuery function without the need of clicking the button?

I have this function below, however I want to make it work on windows load and show the result without clicking the button.
This is the code I use https://raw.githubusercontent.com/SuyashMShepHertz/indexedDB_sample/master/index.html
How to do this?
$("#getBtn").click(function(){
var type = 'permanent';
var request = db.transaction(["hashes"],"readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event){
$("#result").html("Name : "+request.result.name);
};
});
just put your code in
$( window ).load(function() {
//Code Here
});
If you need it both on click and initially when the page loads, make it a reusable function:
function doTheThing() {
var type = 'permanent';
var request = db.transaction(["hashes"], "readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event) {
$("#result").html("Name : " + request.result.name);
};
}
Then call it from both places you need it:
On page load
On click
To call it on page load, just make sure your script is at the end of the HTML (just before the closing </body> tag; this is best practice unless you have a good reason for doing something else) and call it:
doTheThing();
If you can't put the script at the end of the HTML, you can use jQuery's ready callback instead:
// Concise, but easy to misunderstand:
$(doTheThing);
// Or more verbose but also more clear:
$(document).ready(doTheThing);
(See note below about doing it directly or indirectly.)
To call it on click, hook it up, either directly or indirectly:
// Directly
$("#getBtn").click(doTheThing);
// Or indirectly
$("#getBtn").click(function() {
doTheThing();
});
The only reason for hooking it up indirectly would be to avoid having it receive the event object jQuery will pass it automatically, and to avoid having its return value examined by jQuery to see if it should stop propagation and prevent the default event action.
To avoid creating globals, I'd make sure the entire thing is in a scoping function:
(function() {
function doTheThing() {
var type = 'permanent';
var request = db.transaction(["hashes"], "readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event) {
$("#result").html("Name : " + request.result.name);
};
}
doTheThing();
$("#getBtn").click(doTheThing);
})();
just put it in $(document).ready, like this
$(document).ready(function(){
var type = 'permanent';
var request = db.transaction(["hashes"],"readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event){
$("#result").html("Name : "+request.result.name);
};
});

jquery scroll bottom to top, prepand and ajax

I need help creating a finite scroll bottom to top. Something like facebook messages.
I have checked this question but doesn't seem to work for me the way it supposed to. The problem is when I reach the top of the div and the end of the message list, it scrolls down and I can't see the the first few messages. How do I stop this from happening
And also, when new messages are prepended, the existing messages are pushed down, causing the user to lose their "viewing" place.
Here is what I have:
$(document).ready(function(){
$('#message_board').scrollTop($('#message_board')[0].scrollHeight);
});
$('#message_board').on('scroll', function() {
var scroll = $('#message_board').scrollTop();
if (scroll == 0) {
// Store eference to first message
var firstMsg = $('.bubble-left:first, .bubble-right:first');
// Prepend new message here
var content;
$.get("ajax/scripts/msg_lst.php?p=<?php echo htmlentities(isset($_GET['p']) ? $_GET['p'] : ''); ?>&f=" + ($('.bubble-left, .bubble-right').length), function(data){
content= data;
$('#message_board').prepend(content);
});
// After adding new message(s), set scroll to position of
// what was the first message
$('#message_board').scrollTop(firstMsg.offset().top);
}
});
your problem is here
$('#message_board').scrollTop(firstMsg.offset().top);
you can try this instead
$('#message_board').scrollTop(1);
or try to comment that line of code
//$('#message_board').scrollTop(firstMsg.offset().top);
but I think you should use scrollTop after prepend()
$('#message_board').prepend(content).promise().done(function(){
$(this).scrollTop(1);
});
finally .. add a specific class to the elements you want to prepend it and scrollTop the div to last element with this class name and after prepend() use removeClass() to remove this class again
$('#message_board').on('scroll', function() {
var scroll = $('#message_board').scrollTop();
if (scroll == 0) {
$(this).prepend(content).promise().done(function(){
$(this).scrollTop($('.newAppend:last').offset().top);
$('.newAppend').removeClass('newAppend');
});
}
});
Demo here
Note: wrap all your code inside $(document).ready(function(){// all of
your code here });
Make sure to scroll after the message has been prepended.
The $.get accepts a callback which is executed once you get a response from the server.
You should move .scrollTop there as well, as you want to execute that function after you've prepended the content, inside the callback. As everything outside the callback will usually be executed before that callback.
Something like this:
$(document).ready(function(){
$('#message_board').scrollTop($('#message_board')[0].scrollHeight);
});
$('#message_board').on('scroll', function() {
var scroll = $('#message_board').scrollTop();
if (scroll == 0) {
// Store eference to first message
var firstMsg = $('.bubble-left:first, .bubble-right:first');
// Prepend new message here
var content;
$.get("ajax/scripts/msg_lst.php?p=<?php echo htmlentities(isset($_GET['p']) ? $_GET['p'] : ''); ?>&f=" + ($('.bubble-left, .bubble-right').length), function(data){
content= data;
$('#message_board').prepend(content);
// After adding new message(s), set scroll to position of
// what was the first message
$('#message_board').scrollTop(firstMsg.offset().top);
});
}
});
So, I finally figured it out. Something was stopping the $('#message_board').scrollTop(firstMsg.offset().top-curOffset); event. I tried .unbind and .off, it never work. So what I did is added that line to the success attribute of ajax.
$(document).ready(function(){
$('#message_board').scrollTop($('#message_board')[0].scrollHeight);
});
$('#message_board').on('scroll', function() {
var scroll = $('#message_board').scrollTop();
if (scroll < 1) {
// Store eference to first message
var firstMsg = $('.bubble-left:first, .bubble-right:first');
var curOffset = firstMsg.offset().top - $('#message_board').scrollTop();
// Prepend new message here
var content;
$.get("ajax/scripts/msg_lst.php?p=<?php echo htmlentities(isset($_GET['p']) ? $_GET['p'] : ''); ?>&f=" + ($('.bubble-left, .bubble-right').length), function(data){
content= data;
$('#message_board').prepend(content);
$('#message_board').scrollTop(firstMsg.offset().top-curOffset);// <<---- Had to add this event to the ajax success function
});
}
});

How can I combine that javascript and jQuery function to hide a button?

I downloaded the File upload script called Simple Photo Manager.
Since I'm more familiar with jQuery functions I want to use them in combination with the already existing JS code from that script.
I basically want to hide the Delete button when it's clicked.
Why is the Delete button not being hidden after I click on it?
(Note: the JS files are correctly included into the HTML file)
Also, the delLink.removeChild and delLink.appendChild are useless here because it was originally intended for a Delete/Restore switch link, but I decided to go for a button instead.
Thanks a lot if you can help me.
The html code is:
<input type='button' id='deleteit' onClick="deleteLinkOnClick
(this, 'delFlag<?=$imgid?>')">
The JS code for creating that element when an image is uploaded is:
var image_del_link = par.createElement('input');
image_del_link.type = "button";
image_del_link.value = "Delete";
imgdiv.appendChild(image_del_link);
The function for the onclick is: (I tried to write the jQuery function at the bottom)
function deleteLinkOnClick(delLink, delFlag) {
var par = window.document;
var imgDiv = delLink.parentNode;
var image_hidden = delFlag == '' ? imgDiv.childNodes[2] : par.getElementById(delFlag);
if (image_hidden.value == '1') {
image_hidden.value = '0';
delLink.removeChild(delLink.childNodes[0]);
delLink.appendChild(par.createTextNode("Restore"));
delLink.style.color = '#FF0000';
}
else {
image_hidden.value = '1';
delLink.removeChild(delLink.childNodes[0]);
delLink.appendChild(par.createTextNode("Delete"));
delLink.style.color = '#64B004';
}
$(document).ready(function(){
$(image_del_link).click(function(){
$(this).hide();
});
});
}
Here it is.
$("#deleteit").click(function(){
$(this).hide();
})
Try :
$("#deleteit").live("click", function(){
$(this).hide();
});

Javascript and JQuery conflict

I'm not very expert in using javascript and jquery but I'm working with them for a client.
I have encountered a problem using two script: the first one makes a top panel sliding, the second is in a form. This one is used in order to hide or show a particular field basing on the drop down list choice.
I've found that if I disable the first script (the panel), the second script is working fine and vice versa. I tried usign JQuery noConflict() in the head of the page but nothing happened.
Here the code of the first script (sliding panel):
$(document).ready(function () {
// Lets make the top panel toggle based on the click of the show/hide link
$("#sub-panel").click(function () {
// Toggle the bar up
$("#top-panel").slideToggle();
// Settings
var el = $("#shText");
// Lets us know whats inside the element
var state = $("#shText").html();
// Change the state
state = (state == 'Nascondi' ? '<span id="shText">Entra</span>' : '<span id="shText">Nascondi</span>');
// Finally change whats insdide the element ID
el.replaceWith(state);
}); // end sub panel click function
}); // end on DOM
Here the JS code for the form (hide/show field):
$document.addEvent('domready', function () {
$('motivo_contatto').addEvent('change', function () {
if ($('motivo_contatto').value == 'Invia CV') {
$('upload_file').style.visibility = 'visible';
} else {
$('upload_file').style.visibility = 'hidden';
}
});
$('upload_file').style.visibility = 'hidden';
});
});
Can anyone help me ? Thank you and have a nice day!
you're using 2 different ways to add things to happen to the document ready event:
$(document).ready(function(){ ... });
and
$document.addEvent('domready', function() { ... });
maybe if you just use one it works; maybe the code below will work; I put it all in the first option to run code on document ready:
I edited below code and removed all mootools code; so it might work now.
$(document).ready(function(){
// Lets make the top panel toggle based on the click of the show/hide link
$("#sub-panel").click(function(){
// Toggle the bar up
$("#top-panel").slideToggle();
// Settings
var el = $("#shText");
// Lets us know whats inside the element
var state = $("#shText").html();
// Change the state
state = (state == 'Nascondi' ? '<span id="shText">Entra</span>' : '<span id="shText">Nascondi</span>');
// Finally change whats insdide the element ID
el.replaceWith(state);
}); // end sub panel click function
document.getElementById('motivo_contatto').onchange = function() {
if(document.getElementById('motivo_contatto').value == 'Invia CV') {
document.getElementById('upload_file').style.visibility = 'visible';
} else {
document.getElementById('upload_file').style.visibility = 'hidden';
}
};
document.getElementById('upload_file').style.visibility = 'hidden';
}); // end on DOM
Mixing up two different libraries. Not a good idea.
If you want to keep on following on that pattern, wrap one of the function on a different function and call if from another.
Like:
function moo() {
$('motivo_contatto').addEvent('change', function () {
if ($('motivo_contatto').value == 'Invia CV') {
$('upload_file').style.visibility = 'visible';
} else {
$('upload_file').style.visibility = 'hidden';
}
});
$('upload_file').style.visibility = 'hidden';
});
}
Then call it from another
$(document).ready(function () {
moo(); // Call the moo function
// Lets make the top panel toggle based on the click of the show/hide link
$("#sub-panel").click(function () {
// Toggle the bar up
$("#top-panel").slideToggle();
// Settings
var el = $("#shText");
// Lets us know whats inside the element
var state = $("#shText").html();
// Change the state
state = (state == 'Nascondi' ? '<span id="shText">Entra</span>' : '<span id="shText">Nascondi</span>');
// Finally change whats insdide the element ID
el.replaceWith(state);
}); // end sub panel click function
}); // end on DOM
Check this answer, if you want to use both libraries side by side

Categories