I'm total beginner in JavaScript. The problem is that the code works only when I click on the text two times. I need same, but with one click. The code is on the link:
http://jsbin.com/uTizoKe/1/edit?html,output
I'd really appreciate any help. Thank in advance
Move your script tag to the end of the body of the HTML, and remove the onclick handler from the table tag. This works (here's the jsbin):
<script>
document.getElementsByTagName('table')[0].onclick = setTDOnclickEvents();
function setTDOnclickEvents() {
var allTDs = document.getElementsByTagName("TD");
for (var i in allTDs) {
allTDs[i].onclick = function () {
txtCellData.value = this.innerHTML;
}
}
}
</script>
Another option (rather than calling your function based on a table click) is to simply do this:
<script>
var allTDs = document.getElementsByTagName("TD");
for (var i in allTDs) {
allTDs[i].onclick = function () {
txtCellData.value = this.innerHTML;
}
}
</script>
Another option is (if you want to use the script in the head of the document), put everything as a function inside of window.onload.
Additionally, it generally a good practice to try to avoid relying on putting event handlers inside HTML elements themselves, and rather handle all that stuff inside your JavaScript.
Remove the onclick from the table and add it as onload to the body
DEMO
Alternatively, you can use window.onload instead of putting it directly in the body
DEMO
The problem is that you have an onclick attached to the table which calls setTDOnclickEvents. So, only when the user clicks the table will that onclick occur.
What you really want is to bind your elements within the table when the page loads. Using jQuery you could do...
$(function() {
setTDOnclickEvents();
});
Replace
<body>
by
<body onload="setTDOnclickEvents()">
There are other ways to do that, like you could just write :
document.onload = setTDOnclickEvents;
Inside your JavaScript
You need to bind your function to an event for it to be fired at all, if it's inside head.
I'd expect your code not to work at all, strange that it does. Perhaps some default behavior somewhere, not worth investigating...
PS: I just saw that you're biding the click event for table to the function, so that would explain the strange behavior. Yeah, remove that.
The problem is that you're calling setTDOnclickEvents() on click of the table element. So you're not attaching the click events until after you've clicked the first time.
Instead, you can move this into the body onload attribute.
There are some other improvements you could make to this code to, to make it simpler and more up-to-date. If interested, please let me know, I'd be happy to help.
Related
I just wanted to know about any downsides to calling click functions inside a main function rather than in the $(document).ready(function() {});. This is what i mean
function tester() {
$('.className-1').click(function() {
var cmtpid = $(this).attr('data-cmtpid');
alert(cmtpid);
});
$('.className-2').click(function() {
var pid = $(this).attr('data-pid');
alert(pid);
});
}
tester();
UPDATE : the tester() function will only be called once, this is all mainly because I want to avoid inline html onclick=""
Since I noticed you're using jQuery. Perhaps consider adding unbind("click") after the selector to ensure you don't accidentally bind the click more than once causing multiple executions upon click.
Also there isn't any REAL downside but I would HIGHLY recommended putting that java-script at the very end of your html document to ensure the DOM is loaded.
Example:
$('.className-1').unbind("click").click(function(){
});
I'm working on a WordPress website.
All I want to do, add the attribute onclick="off() to an existing div class via javascript (so that the div always has this attribute when the site is loaded). the content plugin I use creates div's automatically, so instead of editing the source code each time, this seems like a nice and fast solution.
right now I'm trying this, but it doesn't work (i know almost nothing about js):
function myfunction() {
document.getElementById("#content_al").setAttribute("onclick","off")
}
I read many threads but didn't get it to work, can anyone help me :)?
off in setAttribute should be off()
Do not pass # in document.getElementById("#content_al"), instead pass plain id i.e. content_al
function myfunction() {
document.getElementById("content_al").setAttribute("onclick", "off()")
}
function off() {
console.log("clicked on off!");
}
myfunction();
<div id="content_al"> Some Content </div>
try jquery. it's easy
jQuery("#content_al").click(function(){
//do action
});
this code defines a click event for your element and you can write your action to run after event fired.
For adding an event handler you should use addEventListener. Below is how you can do it with vanilla javascript.
function myfunction() {
document.getElementById("content_al").addEventListener("click",off)
}
where off is a function
Below is a working snippet. Hope this helps :)
function toggleDisplay() {
let display = document.getElementById("content_al").style.display;
document.getElementById("content_al").style.display = display == "none" ? "block" : "none";
}
function myfunction() {
document.getElementById("hide").addEventListener("click", toggleDisplay);
}
myfunction();
<div id="content_al"> Some Content </div>
<button id="hide">Hide/Show</button>
I am trying to create a simple drag and resize system and I am having problems with adding event listeners to my dividers. Instead of adding the horrendous amount of event listeners to my HTML to every single divider with the class "draggablePanel":
<div id="content">
<div class="draggablePanel" onmousedown='dragShift.dragStart(this,this.parentElement,event)' onmouseup='dragShift.dragEnd(this.parentElement); dragShift.dragHover(this,this.parentElement,event)' onmouseenter= 'dragShift.dragHover(this,this.parentElement,event)' onmouseleave='dragShift.dragEnd(this.parentElement),dragShift.dragLeave(this.parentElement)';>
Content
</div>
</div>
I'm trying to use addEventListeners() for the job:
function addDragPanels(panelArrayName) { //Add the mouse event listeners to draggable panels
if (document.getElementsByClassName) { //Access every divider with the "draggablePanel" class
var divEle;
var draggablePanels = document.getElementsByClassName(panelArrayName);
for(var ctr=0;ctr<draggablePanels.length;ctr++){
divEle = draggablePanels[ctr];
divEle.addEventListener('mousedown', dragShift.dragStart(this,this.parentElement,event),false); //How do i go about editing this?
divEle.addEventListener('mouseup', dragShift.dragEnd( .... etc
}
}
}
if (document.readyState === "complete") {
addDragPanels("draggablePanel");
}
Basically, I am using three arguments: this,this.parentElement,event. How do I correctly pass these arguments using Javascript when I am using addEventListener()? I need the "event" argument to track mouse position in my dragging Javascript functions.
Thanks in advance for any help rendered. Sorry if this question is stupid has been asked before but I just couldn't find the solution anywhere (or maybe I don't know where and what to look).
Where you get this 'dragShift' element? Please refer me to the source.
Some browsers don't support 'addEventListener()'.
Hence, you can use:
divEle.onmousedown = function(){dragShift.dragstart(this,this.parentElement,event);};
or make an anonymous function then put it inside:
divEle.addEventListener('mouseup',function(){dragShift.dragStart(this,this.parentElement,event);},false);
Please let me know if any of it works!
I have a website with the following code for a specific element:
<textarea id="textToTranslate" onfinishinput="dothis()" rows="5"></textarea>
onfinishinput waits for the user input and check if he is stopped. If he stop typing, the function dothis is called throught $('#waitUserInput').live() function.
The tricky part of my question is, how to change the above line to be completely jQuery.
The jQuery dat correspont to the dothis() function is the following:
// Detect if user input stops
$('#waitUserInput').live("keyup", function(e)
{
startTypingTimer($(e.target));
});
var typingTimeout;
function startTypingTimer(input_field)
{
if (typingTimeout != undefined)
clearTimeout(typingTimeout);
typingTimeout = setTimeout( function()
{
eval(input_field.attr("onfinishinput"));
}
, 250);
}
Javascript dothis() function:
function dothis(){
// Ajax call when called
{
Now, when I go to http://validator.w3.org, I have one error, and yes it is about the above code:
Attribute onfinishinput not allowed on element textarea at this point.
<textarea id="textToTranslate" onfinishinput="dothis()" rows="5"></textarea>
The question is, is it possible to turn the onfinishinput javascript attribute out of the textarea, but so that is is functioning the same?
I know it is a little complex, but I hope someone can help.
Why not just change:
eval(input_field.attr("onfinishinput"));
To:
dothis();
And then remove the 'onfinishinput' attribute from your textarea?
There is no such attribute called 'onfinishinput' for the TEXTAREA so the validator is correct. Including it does in fact violate the standard.
It appears that what you are trying to do is to be able to have a different handler for each TEXTAREA on a page so that you can take different actions. If that is the case, why not just have your jQuery call dothis() unconditionally and pass the control that fired the event as a parameter?
You could then put control-specific handling in your dothis() function based on the ID of the passed control.
How about binding the event differently and removing the attribute:
$('#textToTranslate').bind('onfinishinput', dothis');
You'd then need to trigger the event using jQuery's trigger (see http://api.jquery.com/bind/)
Can anyone help, seem to have an issue placing a onclick event of an anchor tag, it works on an image.. I have this
this.whereAreWe = document.getElementById('where_are_we');
this.whereAreWe.onclick = this.whereAreWe;
I have placed a A tag using the id of "where_are_we" ...
but it never executes.. if I change it to an image it works..
I also put the href="#"
Is there something special about anchor tags and applying the onclick via code?
I also tried removing the href, If I remove the href it doesn't show me the little hand icon.
I have put a breakpoint in the function and with an image it enters but using the anchor it doesn't
Any ideas?
The code you provided is confusing. The following code works correctly for me:
a link
<script type="text/javascript">
var whereWeAre = document.getElementById("whereWeAre");
function testClick() {
alert("You clicked!");
}
whereWeAre.onclick = testClick;
</script>
If your example was a little more specific we could probably be more helpful.
The are 2 problems with your javascript. The use of the "this" and the binding of the onclick event back to the reference of the DOM element for the HREF. Try this instead:
var whereAreWe = document.getElementById("where_are_we");
whereAreWe.onclick = function(){
alert("Click event on Where are We");
return false;
};
I also tried removing the href, If i remove the href it doesn't show me the little hand icon.
You need the 'href' attribute for the 'a' tag in order to specify the URL of the destination document or web resource. In case you do not specify it - mouseover doesn't change the cursor. Of course you could use CSS to modify that but that is a different question.