For a web based project, I am using jQuery. In one part of the code, there is data that gets dynamically added to the screen on the client side based on the activity of other users connected to the server. I want to write a code that will allow me to execute a function when a client clicks on the data.
To elaborate a little bit, there is a list which shows which members are online. When a new client connects, his name is added to the list and all other users can see on their screen that he is online. When another user clicks on his name, he sends a message request.
This is the relevant jQuery code:
$('#inc').append("<br><i onclick='accept()'>"+data.plr+"<i><br>")
And the accept function is defined under this block which is within another function, so like
function a(){
$('#inc')....
}
function accept(){
//...
}
However, when the code runs I get an error which says accept() is not defined
How do I solve this problem?
Maybe you can do it in that way...
$('#inc').append("<br><i>"+data.plr+"<i><br>")
$('#inc i:last-child').click(accept);
I did a small CodePen to let you see the code in action
https://codesandbox.io/embed/frosty-jang-fvk3j
I've always done it this way. I find this easier.
$('#inc').append("<br><i class="child">"+data.plr+"<i><br>")
$('.child').on("click",function(){
//your code here
});
You can do it with this way as well :
jQuery(function(){
click_link = $('<a class="" href="#">Click here</a>');
click_link .bind("click", function(){
alert('DO something');
});
$('.your_dom').append(click_link );
});
Write it using jQuery methods:
var $i = $('<i>').text(data.plr).click(function(event) {
//handle here onClick event
}); //or if you have the function already declared just write .click(accept);
$('#inc').append('<br />', $i, '<br />');
https://api.jquery.com/click/
Related
I am working on ListControl and one of the columns has Delete link which I am formatting using HTMLTemplate as follows:
<a href="javascript: app.showConfirmation()" >Delete</a>
My Javascript looks as follows:
define(["sitecore", function (Sitecore) {
var DestinationRules = Sitecore.Definitions.App.extend({
initialized: function () {
this.processDestinationRules();
},
showConfirmation: function () {
alert('here');
},
});
return DestinationRules;
});
For some reason, I am not able to call showConfirmation(). It says is undefined. I even tried Sitecore.Speak.app.showconfirmation() but not working.
I tried my best to search online but not able to find much help around calling function through controls embedded inside HTMLTemplate.
My next step is to call DialogWindow.
Please if you can help me with the syntax of the above. Thanks in advance.
Fixed it in a different way.
I wanted to show in-line Delete button in each row of the Listcontrol. Could not figure out way to call the
javascript: app.showConfirmation()
I changed the way to delete the record:
Have one Delete button outside the ListControl.
Enable/Disable the Delete button based on binding ListControl.HasSelectedItem.
On click of the Delete button, call showConfirmation()
As of now seems to be a better way. Sitecore itself uses similar approach for "Kicking off" users. Can be found here:
/sitecore/client/Applications/LicenseOptions/KickUser
Hope that helps. Thanks.
Finally, managed to do this. Always knew that it can be done this way but did not like the way its done.
The Delete link in List control opens up a confirmation Dialogue window. And if user selects Yes then it calls the app.onDeleteYes()
The HtmlMarkup for the column:
Delete
Added a button called btnDelete with visibility set to false.
Added following function, outside the scope of App:
var destinationRulePage = (function () {
var self = this;
self.showDeleteDialog = function (id) {
$("button[data-sc-id='btnYes']").attr("data-sc-click",
"javascript:app.onDeleteYes(" + id + ");");
$("button[data-sc-id='btnDelete']").click();
}
return self;
}())
This does the job for me. Thanks.
Is it possible for a button to call a function that would 'prettify' a dynamic <code><pre>? I can't get it to work.
After the page loads, the initial <code> is prettified(?), but when I change it and call prettyPrint() afterwards, it no longer works.
Example: http://jsfiddle.net/uwBjD/2/
Edit: Sorry, I was using a local prettify.js. Updated it, still encountered the same error.
Apparently after the code is prettified, an additional class is added which is prettyprinted. Anything with the class of prettyprinted is not re-prettified. You need to remove that class before recalling the function:
$('input[type=button]').click( function() {
$("#jsExample").text(" var user = 'private'; //Do NOT store your API Key on a script.")
.parent().removeClass("prettyprinted");
prettyPrint();
});
http://jsfiddle.net/uwBjD/3/
I have got this html:
<a style="display:block; padding:100%; text-decoration: none;" href="http://google.com " class="Jasmin" id="target_site_to_visit">
<span data-app-id="88" class="btn" id="visit_site" style="right:22px; top:65px; padding:5px;z-index: -99999;">VISIT SITE</span>
</a>
and this jquery:
(function($){
$('#target_site_to_visit').live('click',function(event){
event.preventDefault();
var appName=$('#target_site_to_visit').attr('class');
$.post('db/update_site_viewed.php',{ name:appName }, function(data){
throw new Error("AppName: "+appName);
},'html').error(function(data){
throw new Error("Error: "+data.responseText);
});
document.location.href=$('#target_site_to_visit').attr('href');
}); })(jQuery);
A problem exists, whenever the button is clicked.. the post method is executed which puts the data into the database. But that only happens when the last line in jquery doesnt exist: document.location.href.. the redirection effects the post somehow..and doesnt probably doesnt give the post method to execute..resulting in no record being inserted to the db (or in other post method doesnt execute).. is it possible that that is the cause..cause the redirection does effect the execution of the post method
This will solve your problem
<script type="text/javascript">
$('#target_site_to_visit').live("click",function(event){
event.preventDefault();
var appName=$('#target_site_to_visit').attr('class');
$.post('db/update_site_viewed.php',{ name:appName }, function(data){
// console.log("AppName: "+appName);
},'html').error(function(data){
// console.log("Error: "+data.responseText);
});
// document.location.href=$('#target_site_to_visit').attr('href');
});
But use .on() instead of .live().LIke
<script type="text/javascript">
$(document).on("click",'#target_site_to_visit',function(event){
event.preventDefault();
var appName=$('#target_site_to_visit').attr('class');
$.post('db/update_site_viewed.php',{ name:appName }, function(data){
// console.log("AppName: "+appName);
},'html').error(function(data){
// console.log("Error: "+data.responseText);
});
// document.location.href=$('#target_site_to_visit').attr('href');
});
</script>
You need to pass the event to listen for (in this case click) to the live method.
$("#somediv").live("click", function () {
console.log("you clicked it");
});
Also, as the other answerer said, you should use on as opposed to live, here is an article that explains why: http://bitovi.com/blog/2011/04/why-you-should-never-use-jquery-live.html
You don't appear to have specified the type of event. It should be 'click', and if my extremely limited knowledge of jQuery syntax is correct, it should be the first parameter before your callback.
To be on the safe side, I like to have any link that is intended to be handled by JavaScript have href="javascript:void(null);". That way, even if the event handler fails to cancel the event, nothing will happen anyway. It's also less confusing for the users to see a JavaScript link in their status bar when you hover over it, than a link to Google.
First I am using the jQuery colorbox plugin that is working fine so far but then I want to close the colorbox using a button. Unfortunately I can't just trigger the click event on that button by selecting its ID using jQuery, instead of that the button must call a javascript function called closepan() (this behavior is unfortunately mandatory for me).
I tried to create the function
closepan() {
$.colorbox.close();
}
first case : inside the
$(document).ready(function(){...});
but then I got the error closepan is undefined.
second case : before the
$(document).ready(function(){...});
but then it's the colorbox method that is undefined!
I gave up after gazillion hours of fiddling with several solutions I've found all around stackoverflow.com regarding this topic! I can't figure out how to make this working!
In other words, how to create a function named closepan() that can execute $.colorbox.close(); while being available globally for my button?
No matter where you create a variable or function if you create it on window it will be available globally.
window.closepan = function() {
// hello there
}
function closepan() {
if($.colorbox) {
$.colorbox.close();
}
}
However, at the point where someone clicks your button all external scripts should have been loaded so that check shouldn't be necessary...
Don't forget to put the keyword function in front of your declaration...
function closepan() {
$.colorbox.close();
}
Working JSFiddle
I am trying to give a button an onclick event when a certain thing on a page changes. I have tried to do it many different ways and none have worked. What am I doing wrong?
Below are what I have tried.
document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
document.getElementById(subDiv).onclick = "alert('Error. There is an error on the the page. Please correct that then submit the page');";
function redErrorAlert()
{
alert('Error. There is an error on the the page. Please correct that then submit the page');
}
document.getElementById(subDiv).onclick = redErrorAlert;
document.getElementById(subDiv).setAttribute('onclick',redErrorAlert(), false);
document.getElementById(subDiv).setAttribute('onclick','redErrorAlert()', false);
Note: subDiv is a variable containing the id of the element.
You need to wait for the DOM tree to be created before you do queries on it.
Make sure that this all happens within a context that is created after the DOM tree has been built:
window.onload = function() {
document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
};
document.getElementById() takes a string containing the ID of the element you're trying to find. Assuming you're looking for the element with id 'subDiv', you should be calling document.getElementById('subDiv').
(It's also possible that the variable subDiv in your code is a string containing the ID, but since you didn't mention it I'm assuming that it doesn't.)
EDIT: If you were to go with virstulte's suggestion of using jQuery, you'd attach a function to the document.ready event in order to ensure that the DOM has been built by the time your code runs. Example:
$(document).ready(function() {
$("#subDiv").click(function() { alert("Test!"); });
});
This sounds like jQuery territory here. Once you learn the ins and outs of jQuery, things like this are a snap to take care of, and you'll find yourself writing a lot less JavaScript.
First, get jQuery from http://jquery.com/
Then put this in your code to bind the event:
$('#idOfElementToBindClickEvent').click(function(){
alert('Error.');
});
jQuery basically provides a way to manipulate elements using CSS-like selectors.
try
document.getElementById(subDiv).onclick = alert('Error. There is an error on the the page. Please correct that then submit the page');
or
function redAlert() {
alert('Error. There is an error on the the page. Please correct that then submit the page');
}
document.getElementById(subDiv).onclick = redAlert();
First case: you need to call the function, and you've assigned a string
Second case: you've assigned a function and you were not calling this function