I have assigned a onClick event to textbox. When I am clicking on textbox, I want to execute the click event of div also. How to do that in Javascript?. The div and textbox are not nested they are on different position in document.
Thanks in advance for the Help.
I would recommend using a function that is called by both.
You need to know even bubbling in order to do that.
I recommend reading PPK's blog post about events. It's a bit old, but it weathers the test of time well. See:
http://www.quirksmode.org/js/events_order.html
If the elements are nested the event will bubble up (if you aren't cancelling it) so:
<div onclick="foo()">
<input type="text" onclick="bar()" />
</div>
Will result in a call to bar then foo. This is a bit of a kludge though since you don't really want to have inline event binding if you can help it. This is one of those cases where use jquery might be appropriate since $('#mydiv, #myinput').click(baz) is quite clean.
Try this:
function twoActions(){
var textboxId = document.getElementById("textboxId");
var divId = document.getElementById("divId");
textboxId.style.border = "red"; // action one
divId.style.border = "red"; // action two
}
you tie this function to the textbox - onClick it will change the border color of the text box and that of the Div.
If you're not nesting the divs, you'll need to explicitly call the .click() of the div separately.
function textEvent() {
// Do all the stuff you want to do for the textbox
// Fire the event for the div too
div = document.getElementById('#secondDiv');
div.click();
}
I am reading it as if you have 2 different functions. We'll just say textbox(); and div();
your onclick for the textbox should read
onclick="textbox(); div();"
That should call both functions on the same event, where with the div you can put only the div() function or both like the example above. Just seperate the function calls with a semi-colon.
Related
I have a function that dynamically creates div elements based upon whatever input is given, and lets them choose certain items by clicking on each div. I have it so that if the div is clicked, a function (named checkToggle) is called that makes it looks like it is selected and adjusts some related variables. There is a checkbox in the div element that is toggled by this function (hence its name). Long story short, I had to jump through some hoops to get it to work, most of which I don't even remember. Please don't ask me about that.
The point of this question is this. I initially used the following JavaScript code to run the function when the checkbox was clicked. It was assigned by the main function, which created these div elements using a for loop.
document.getElementById(`${itemID}-checkbox`).onclick = function() {
checkToggle(`${itemID}-checkbox`);
};
This works, but I wanted to try to convert all of my onClick functions to JQuery. Here is the JQuery alternative I created.
$(`${itemID}-checkbox`).on(`click`, function() {
checkToggle(`${itemID}-checkbox`);
});
While the code itself seems to be fine, it does not work. It seems as if JQuery functions cannot be created like this in a for loop or something. It is applied after the element is created and put in its place, so I don't think it has anything to do with the element not being ready. I am also having the same issue with 2 other similar cases. Any idea as of why this isn't working?
Let me know if more information is needed and if so, what kind of information is needed.
You need to update the selector to Target HTML id using the # character. Simply prepend the character to the query:
$(`#${itemID}-checkbox`).on(`click`, function() { checkToggle(`${itemID}-checkbox`); });
It would also apply to DOM methods querySelector or querySelectorAll as well.
Hopefully that helps!
What is the possibility of the $subject?
Just imagine I have a foo html element
e.g.
<div data-toggle="loader">...</div>
and have a jquery function binded to it by default,
e.g.
$(document).ready(function(){
$('[data-toggle=loader]').loader();
});
So this will change the DOM element to something like,
e.g.
<div data-toggle="loader" class="active" style="height:800px">...</div>
So what I want to do is prevent applying the changes to the foo element, if it has a class name .example. So the catch is, I cannot touch the default execution code. But I can write another function to handle it. That is the problem I'm facing right now. Any possibility of achieving this?
Easiest would be to either change the DOM structure, i.e. so the JS no longer finds the element, or overwrite the jQuery plugin with something innocuous. Do this in a script after the plugin script itself has loaded.
jQuery.fn.loader = jQuery.noop; //$.noop is an empty, pointless function
[EDIT]
In light of the OP's comment, the best bet may be to store a clone of the element then replace the original element with it after the plugin has fired.
var
el = $('.some-element'),
clone = el.clone(1, 1);
//some time passes... plugin is called... does nothing to element
el.replaceWith(clone);
I've got this situation:
There is a calendar script to pick a date. When the date is picked a function called onclick to make a select box available for time pick. Now its not like its display:none-->display:block, the select being generated by JS. My goal is to customize this select. For that I got a jquery script "custom.select" which just turns the select to spans. The problem is that if I add the call for this script to the onclick right after the calendar call it does not take. I am pretty sure its because at that stage the html for the select is not injected yet. If I call the custom.select function from the firebug console after the select is visible - it works just fine.
So the question is: how do I call it so it will do its magic on select box?
Thanks
Use delegation with .on():
$(function(){
$(document).on('click','.classdynamic',function(){
//do stuff here
});
});
You should delegate event to the closest static container of your target element. This means changing $(document).on('click','.classdynamic',function(){...});
by something like: $('#staticContainer').on('click','.classdynamic',function(){...});
Figuring out when elements are added is not an easy task. I answered a similar question here.
The best way would be to have some control on the script that creates the select, and append your code to it. One way to achieve this is with Aspect Oriented Programming (AOP) - not easy either.
With current browsers, the most straightforward way is to use setTimeout in a loop and poll the page until the element exists.
Ok I got this thanks to Christophe! I used the Selector Listeners script from here: http://www.backalleycoder.com/2012/08/06/css-selector-listeners/
It was even more complicated coz the parent was not present either )). So what I did was that I attached the listener to the onclick just after the calendar call lol. I needed to make another function though to make it work with the script, here is the code:
var doSelect = function(){
jQuery('#timeslots').customSelect();
};
jQuery(document).ready(function(){
jQuery('.td_calendar').on('click','#anchor1',function(){
cal.select(document.forms['frmRequest'].startdate,'anchor1','yyyy-MM-dd');
document.getElementById('slots').addSelectorListener('#timeslots', doSelect);
});
});
I'm trying to make a function to check, anytime something is changed on my page, if all input is valid. I thought the best way to do this, rather than attach the function to every input would be to put it on the entire page (hence html/body tag,) but this didn't seem to work in that nothing happened. My code looks like:
<body onchange="removewarn()">
.
form elements
.
.
</body>
and the function
function removewarn(){
if(all input is valid)
{
document.getElementById('warning').style.visibility="hidden";
}
}
The point of which, is to remove a warning put on the page if all elements are not filled in or are not valid.
The onchange event does only work with Form elements, so you will have to add it to every form element. However! there is a easier and cleaner way to do this than doing it inline:
for(i=0; i<document.FormName.elements.length; i++)//gets all the elements of your form.
{
document.FormName.elements[i].onchange = removewarn();//adds the removewarn function to the onchange handler of this element.
}
The onchange event is only supported by inputs, selects and textareas, wich is why your function will never be called if you try to bind it to the body tag.
You will either have to bind it on every input, or to use something like jQuery's delegate method.
Wondered if there was good way to do this, thought I would post to the SO community...
There is a 3rd party web page that I have no control over how it renders, but they allow me to add JQuery.
Using the JQuery, I am creating a nav menu on the side of the page, it will be a list of links. The onclick event of these links I get from existing onclick events already on the page, but when I do a:
var linkLoc = $('#theLink').attr("onclick");
linkLoc returns:
function onclick(event) {
handleJumpTo("com.webridge.entity.Entity[OID[E471CB74A9857542804C7AC56B1F41FB]]", "smartform");
}
instead of what I would expect:
handleJumpTo("com.webridge.entity.Entity[OID[E471CB74A9857542804C7AC56B1F41FB]]", smartform");
I think JQuery is trying to get the event for binding, but I need the actual Javascript markup since I'm creating the HTML dynamically. I guess I could substring the "function onclick(event) {" out, but seems kind of hacky.
Any ideas of an elegant way I could get the onclick markup?
$("#theLink") would return a jQuery object whereas $("#theLink")[0] would give a DOM object. This is a resson that $("#thelink")[0].getAttributeNode('onclick').value would work.
The type of $('#theLink').attr("onclick") is a function, so you can just use that when you bind events to the links.
var linkLoc = $('#theLink').attr("onclick");
$('a#link1').live('click', linkLoc);
Example: http://jsfiddle.net/BdU6f/
You can also run other code in the click handler too, if you need:
var linkLoc = $('#theLink').attr("onclick");
$('a#link1').live('click', function(e){
// Code...
linkLoc(e);
});
Example: http://jsfiddle.net/BdU6f/1/
The "onfoo" attributes have values that are functions, not strings. The semantics of:
<whatever onclick='code code code'>
are that the browser constructs a function object as if you had code that did this:
document.getElementById('whatever').onclick = new Function("event", "code code code");
Thus you don't really need the raw string, since you've got something better: the function itself, ready to be called. You can then bind it as a handler to other elements via JavaScript code, not HTML (which is really a better way to do things anyway). You're using jQuery, you say, so you can use the jQuery ".bind()" API to bind those functions to whatever elements you need.
You should also be aware that there are other ways of binding event handlers to elements, ways that will leave the "onfoo" attributes completely unset.
If I understand where you're going with this, you should be able to assign the returned onclick function straight through to the onclick of your new nav element...
$('#NewNavElement').click($('#theLink').attr('onclick'));
If you need to add additional code to the handler, you can just bind another click handler.
try this;
$('#theLink').getAttributeNode('onclick').value
Revised as per comment:
$('#theLink').get().getAttributeNode('onclick').value