Is there any callback function on click? - javascript

Let's say I have the following link:
<a href="#shippingaddress" onclick="return validateBillingAddress(document.addressInput,'ADDR_CONTINUE_ACTION',event);" >
EDIT
i am using multi page approach to show different section(divs) as a page
in that validate function I am validating the form and if everything is ok then displaying a hidden <div> and after the <div> is visible <spans> are getting applied by jquery mobile framework, untill and unless that div is hidden there is no span, but as that div become visible jquery mobile gets applied on it and appended some spans..i need to access this spans :
<span>blah</span>
So I want to change the text of this <span> after the click event, because the <span> is displayed after the click event.
So is there any way to do this?

In your validate function you can do this:
<div id="someDiv" style="display:none">
<span id="someSpan"></span>
</div>
<script type="text/javascript">
function validateBillingAddress() {
var valid = true;
... // do whatever you need to validate your input here and update valid variable
if (valid) {
$('#someDiv').show();
// if the validation is succesful invoke some function in the framework here
$.ajax({
...
success: function() {
//append the span to the div here
$(#someDiv').append('The span HTML content');
},
...
});
}
}
</script>

You could actually embed the validateBillingAddress into another function, containing the "callback" line as well
function doValidate( event ) {
validateBillingAddress(document.addressInput,'ADDR_CONTINUE_ACTION',event);
$('#spanElement').text( 'new text' );
}
And then
<a onclick="return doValidate( event );" >
Would be even better if you avoided using the onclick property in favor of a non-invasive event handling like
$('#aElement').click( function( e ) {
doValidate( e );
});

Do not use inline javascript...
$("#validate").click(function(){
// validate billing address
});
<a id="validate">Validate</a>
To create a span and attach a listener to it, then append to the div:
$("<span />").click(function(){
$(this).text("New Text");
}).appendTo("#divToShow");
Edit:
Since you haven't provided much information, the only thing I can help you out is:
1- To access all spans within the div, you do:
$("#myDivId span")
2- To access only spans that are direct children of the div, you do:
$("#myDivId > span")
3- To access only the last span within the div, you do:
$("#myDivId span:last")
More than that, only if you provide some actual generated code

Related

Running script after div added

Im using a plugin (Event Organiser Pro) that dynamically creates a div based on the input of a number field - basically it creates a duplicates the form fields depending on the number you enter in the input field.
I need to run some jQuery which is based on those form fields, but obviously cant run it until the div has been created.
How can i run the script once the div has been created? Is it possible to run script when div id has been created? Or something similar?
Yes, you can delegate the DOMNodeInserted event to the body.
function createDiv() {
$('<div />').addClass('test').appendTo($('body'));
}
$('body').on('DOMNodeInserted', '.test',function() {
alert('Created element .test');
})
$("button").on('click', function() {
createDiv();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create</button>
In the example above the click on the button simulates your other script creating the div.
To rewrite the code to work with your setup you can strip the click part out and delegate the event listener to your id:
$('body').on('DOMNodeInserted', '#your_element',function() {
yourFunction();
// call a function here or add your code here directly
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: This example won't work here because the element with that ID does not exist and neither does the yourFunction() function.

Replace a title with an input and update the title on the database

Hi I'm trying to replace a title when clicking on it by a text input in order to modify the title and then submit the modification to the database, I'm using this code :
<div style="font-size: 70%;"><h2 class="outer"><?php echo $designation; ?> </h2></div>
this div is loaded using another script and therefore is not on the original page, so I think we must use the delegate method.
Here is the jquery script I'm using to turn its background color to pink:
<script src="jquery-1.10.2.min.js">
$(document).ready(function(){
$("#right").delegate("h2","click",function(){
$("h2").css("background-color","pink");
});
});
</script>
Any idea how to replace the title in this div by a text input tag ? and any idea how to submit the modification to the database once I click outside the input field ?
thank you
There is no click handler in you code, you can use .on() method
You should use another script tag for loading .js files, your markup is invalid
input element doesn't have closing tag, you should remove the </input>
<script src="jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){ // When the DOM is ready
$(".outer").on('click', function() {
if ( this.children.length ) return;
var text = $.trim(this.innerHTML);
$("<input>").val(text)
.appendTo($(this).empty())
.focus();
}).on('blur', 'input', function() {
// Listening to blur event
// for replacing the element with it's value
$(this).replaceWith( $.trim(this.value) );
})
})
</script>
http://jsfiddle.net/3FKzH/

JQuery does not determine the div class which is printed from ajax

I have html elements that printed in html page using smarty engine , then printed from jquery
the html which is printed from smarty is
<div id="broadcastsXXX" class="broadcast orginal-broadcast highlightedbroadcast">
<i class="dogears"></i>
<div class="content">
...
...
</div>
</div>
and the html which is printed from jquery is the same html code which is printed comming from smarty template as shown above.
I want to remove the css class "highlightedbroadcast" when someone clicked on the div which has the class "content" as shown above
so I do the jquery code:
$(document).ready(function() {
$('.content').click(function() {
$(this).parent().removeClass("highlightedbroadcast");
var broadcastid = ($(this).parent().attr("id"));
});
});
The function is changing the clicked div parent and remove the class highlightedbroadcast.
when the user clicked on the .content div that is printed from smarty template when page loas its remove the highlightedbroadcast css class without any problem. but if the user clicked on the div .content which has been printed from ajax it will not remove the class and do nothing.
I try to add alert('hi') to the function and it also says hi when the user clicked on the .content div which is comes from smarty and do noting when the user clicked on the div which is printed from ajax.
note that the broadcastsXXX is dynamic as broadcasts123 broadcasts124 .. etc
and this is a real example http://jsfiddle.net/samshannaq/FUK5Z/2/
so is there any solution for this?
.click() will only add event handlers to the current DOM.
If you want jQuery events to also apply to any HTML that is subsequently loaded via AJAX, you need to use the .on() event handler rather than .click():
$(document).ready(function() {
$('body').on('click', '.content', function() {
$(this).parent().removeClass("highlightedbroadcast");
var broadcastid = ($(this).parent().attr("id"));
});
});
Either that, or you need to add the click events to HTML that is loaded via AJAX after every AJAX call.
I think you should use 'live', while not just 'bind' or 'click' . When document is ready, the div.content is not rendered at all ( they are rendered through ajax response. ). so change your code to
$(document).ready(function() {
$('.content').live('click',function() {
$(this).parent().removeClass("highlightedbroadcast");
var broadcastid = ($(this).parent().attr("id"));
});
});
may work.

Javascript event accessing when there is another parameter

I am working on a feature where if you click a blurb link, it will display the full description in a preview window; much like the search result preview in search engines, like Google.
I need to pass both the full description text and the event to the handling function so the function knows what to display and where to display (under the blurb).
My question is that what should I pass to the function. Currently I have below and it's not working:
blurb text here
function javascript:DisplayFullDescription(e, fullText){
//find out mouse click position
//display a preview window (div) with description there
}
If you're not using HTML5, personally, I would create a hidden element for the full text with display:none, which I would assign as data to each applicable element, and use that info on click
<a class="clickable" href="#">blurb text here<span style="display:none">blah blah description goes here</span></a>
$('a.clickable').each(function() {
$(this).data('fulltext',$(this).find('span').remove().text());
}).click(function(event) {
event.preventDefault();
$('body').append('<div>'+$(this).data('fulltext')+'</div>');
})
It would be much easier to use jQuery to bind the event handlers, and an HTML5 data-* attribute to store the full text, rather than using onclick attributes.
HTML:
blurb text here
jQuery/JavaScript:
$('a').click(function(e) {
DisplayFullDescription(e, $(this).data('fulltext'));
e.preventDefault();
});
function DisplayFullDescription(e, fullText){
//find out mouse click position
//display a preview window (div) with description there
}
<a id="someID" href="#" data-fulltext="blah blah description goes here">blurb text here</a>
<script>
var element = document.getElementById('someID'); // grab the element by id. (simple for this demo)
element.onclick = DisplayFullDescription; // attach the event handler to the onclick function
function DisplayFullDescription(e) { // because we attached the handler above the Event is passed as the first argument to the function (handler)
var description = this.getAttribute('data-fulltext'); // 'this' now references the element in which the onclick was invoked.
alert(description);
}
</script>
You can try this above and see if it meets your needs.
Considerations:
- This does not need jQuery library to function (it would be overkill to use it for just this)
- This will work cross browser (old and modern)
- This has nothing to do with HTML5 (which is cool... but again, overkill and limiting)
- data-* can be accessed using getAttribute() and does not rely on the element.dataset being available.
However it would benefit you to read up a bit more on Events

Get the element triggering an onclick event in jquery?

I have a form where i've replaced the submit button with an input (with type=button) with an onclick which calls an existing function:
<form accept-charset="UTF-8" action="/admin/message_campaigns" class="new_message_campaign" id="new_message_campaign" method="post">
<!-- some fields -->
<input onclick="confirmSubmit();" type="button" value="Send" />
</form>
In the confirmSubmit, i'd like to be able to dynamically get the form object (to submit it), instead of having to hardcode the form's id, or pass it as part of the call to confirmSubmit(). I'd have thought that i could do this by first getting the dom element that was clicked on, ie something like this:
var form = $(this).parents("form");
where $(this) is the object that called the function, ie the input with the onclick. This doesn't work though. I think it would work if i'd set it up with the .click(function(){ syntax. Can i get the element that called the function in a different way?
EDIT - got the answer from #claudio below, for clarity here's the complete function and call:
<form accept-charset="UTF-8" action="/admin/message_campaigns" class="new_message_campaign" id="new_message_campaign" method="post">
<!-- some fields -->
<input onclick="confirmSubmit($(this));" type="button" value="Send" />
</form>
and the function itself. Note that 'jConfirm' is a method of the jquery-alerts plugin (http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/) but that's not really relevant to this question - the key thing was just to get the form object, not what's subsequently done with it:
function confirmSubmit(caller) {
var form = caller.parents("form");
jConfirm('Are you sure?', 'Please Confirm', function(result){
if (result) {
form.submit();
} else {
return false;
}
});
}
You can pass the inline handler the this keyword, obtaining the element which fired the event.
like,
onclick="confirmSubmit(this);"
If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:
$('#sendButton').click(function(e){
var SendButton = $(e.target);
var TheForm = SendButton.parents('form');
TheForm.submit();
return false;
});
Try this
<input onclick="confirmSubmit(event);" type="button" value="Send" />
Along with this
function confirmSubmit(event){
var domElement =$(event.target);
console.log(domElement.attr('type'));
}
I tried it in firefox, it prints the 'type' attribute of dom Element clicked. I guess you can then get the form via the parents() methods using this object.
It's top google stackoverflow question, but all answers are not jQuery related!
$(".someclass").click(
function(event)
{
console.log(event, this);
}
);
'event' contains 2 important values:
event.currentTarget - element to which event is triggered ('.someclass' element)
event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)
this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)
When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.
First Way: Send trigger element using this
<button id="btn01" onClick="myFun(this)">B1</button>
<button id="btn02" onClick="myFun(this)">B2</button>
<button id="btn03" onClick="myFun(this)">B3</button>
<script>
function myFun(trigger_element)
{
// Get your element:
var clicked_element = trigger_element
alert(clicked_element.id + "Was clicked!!!");
}
</script>
This way send an object of type: HTMLElement and you get the element itself. you don't need to care if the element has an id or any other property. And it works by itself just fine.
Second Way: Send trigger element id using this.id
<button id="btn01" onClick="myFun(this.id)">B1</button>
<button id="btn02" onClick="myFun(this.id)">B2</button>
<button id="btn03" onClick="myFun(this.id)">B3</button>
<script>
function myFun(clicked_id)
{
// Get your element:
var clicked_element = document.getElementById(clicked_id)
alert(clicked_id + "Was clicked!!!");
}
</script>
This way send an object of type: String and you DO NOT get the element itself. So before use, you need to make sure that your element already has an id.
You mustn't send the element id by yourself such as onClick="myFun(btn02)". it's not CLEAN CODE and it makes your code lose functionality.

Categories

Resources