Change the contents of the element's onclick function - javascript

I know it is possible to change different parts of an element such as class, value and html content.
What I am looking for is a way to change the values of the function call itself.
document.getElementById(id).onclick = "javascript:FUNCTION('"+id+"','0');";
The second pass value is what I will be changing. So value "0" can be for example "1" or "2"
Is this possible?
EDIT:
In case this gets going down the wrong road.....
This is what I will be changing with that code.
So then the page ( and script ) is ready to run again with new values
<div id="id" class="stuff" onclick="javascript:function('id','0');" style="cursor:pointer;">
hope that clarifies things a bit more.
RE-EDIT:
Well seems this might not be possible. So will start looking at ways round.

It depends on what you are trying to do, but here is a way of doing it which would not even require the changing of the function.
var myValue = 0
document.getElementById("test").onclick = function (aEvent) {
myValue++;
alert(myValue);
}
See fiddle: http://jsfiddle.net/AqZHZ/

Related

Passing parameter to javascript onclick without using HTML

I can't figure this out. I'm trying to create an onclick handler purely in Javascript.
What I plan to do here is inside this DIV, have a collection of items that I can click on. For now, these items will be numbers from 0 to 9 inclusive. When a number is clicked on, a system message consisting solely of that number should pop-up on the screen. I narrowed my problem down to just the onclick handler definition.
If I use this format:
item[n].onclick=function(n){
handler(n);
}
The handler will fire only when click a number which is correct, but the message that appears is something about mouse event.
If I use this format:
item[n].onclick=function(){
handler(n);
}
The handler will pass a value of -1 which in turn is printed as a message. I think it means "false".
How do I modify this:
item[n].onclick=function(){
handler(n);
}
so that 'n' being used as the handler parameter is the same as the number I click on the screen?
My code is the following:
<div ID="Itemset"></div>
function handler(n){
alert(n);
}
collections=document.getElementById('Itemset');
for(n=0;n<10;n++){
item[n]=document.createElement('DIV');
item[n].innerHTML=n;
collections.appendChild(item[n]);
item[n].onclick=function(n){
handler(n);
}
}
What I'm effectively trying to do if you want to understand it HTML wise is this:
<div ID="Itemset">
<div onclick="handler(0);">0</div>
<div onclick="handler(1);">1</div>
<div onclick="handler(2);">2</div>
<div onclick="handler(3);">3</div>
<div onclick="handler(4);">4</div>
<div onclick="handler(5);">5</div>
<div onclick="handler(6);">6</div>
<div onclick="handler(7);">7</div>
<div onclick="handler(8);">8</div>
<div onclick="handler(9);">9</div>
</div>
Except that I don't want to write out onclick="handler(n);" a million times.
Any advice? and feel free to point to another resource that has the answer I need if there is one.
UPDATE
I'm looking for something compatible with older browsers as well. I'm going to have to not go for the bind function because according to mozilla docs, it works for IE 9+. I'm looking for something that works for IE 7+ as well as other browsers. I might have to go for event listeners if there is no other alternative.
You have a closure issue here (see JavaScript closure inside loops – simple practical example), a simple solution is to use bind to use the current value of n to be a parameter of the handler function
item[n].onclick=handler.bind(item[n],n);
U can use addEventListener and ID for find clicked element...
document.getElementById("Itemset").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a list item
var value_data = parseInt(e.target.textContent);
if(e.target && value_data > -1) {
alert("Malai test:: "+value_data);
//handler(value_data);
}
});
https://jsfiddle.net/malai/tydfx0az/
I found my answer here: https://bytes.com/topic/javascript/answers/652914-how-pass-parameter-using-dom-onclick-function-event
Instead of:
item[n].onclick=function(n){
handler(n);
}
I have to do:
item[n].onclick=new Function('handler('+n+')');
Funny thing is, the word function needs to be capitalized when making a new instance. It's awkward I have to go this route but it works in IE 7+
One alternative is :
function handler(){
alert(this.id);
}
function myFunction() {
var item=[];
collections=document.getElementById('Itemset');
for(n=0;n<10;n++){
item[n]=document.createElement('DIV');
item[n].innerHTML=n;
item[n].setAttribute("id","itemset"+n);
collections.appendChild(item[n]);
item[n].onclick=handler;
}
}
Insert dynamic ids to the elements and when you click on any element retrieve its id using this.id and do whatever you want to do with that value.
That's all.
Hope this helps.

Access html elements created by js in other js functions

I am trying to access html elements that I create in one js function in another function. I have this code
EDIT after comments:
here is a jsfiddle
http://jsfiddle.net/8uTxM/
</button>" +"<button value='1' type='button' class='as' id='c2' onclick='cA(this);'>"
in this function
function cA (element){
var x = element.value;
if (x === allQuestions[questionNumber].correctAnswer) {
element.setAttribute.style.backgroundColor = "green";
++score;
}
}
I am trying to make the button green when it is clicked. However, I get the error:
Cannot set property 'backgroundColor' of undefined
I assume this has something to do with timing, but I cannot figure out why. Especially since the element.value bit works (the++score works fine, every right question adds +1 to the score variable)
One problem that I may guess is you are using "getElementsById"
either go for "getElementById" or "getElementsByTagName"
Why don't you create a <div> in your html/php page which would be empty with the answers class, and then change its id/innerHTML ?

Create a region on HTML with changing values

I am a beginner in HTML and I want to create a region on a HTML page where the values keep on changing. (For example, if the region showed "56" (integer) before, after pressing of some specific button on the page by the user, the value may change, say "60" (integer) ).
Please note that this integer is to be supplied by external JavaScript.
Efforts I have put:
I have discovered one way of doing this by using the <canvas> tag, defining a region, and then writing on the region. I learnt how to write text on canvas from http://diveintohtml5.info/canvas.html#text
To write again, clear the canvas, by using canvas.width=canvas.width and then write the text again.
My question is, Is there any other (easier) method of doing this apart from the one being mentioned here?
Thank You.
You can normally do it with a div. Here I use the button click function. You can do it with your action. I have use jquery for doing this.
$('.click').click(function() {
var tempText = your_random_value;
// replace the contents of the div with the above text
$('#content-container').html(tempText);
});
You can edit the DOM (Document Object Model) directly with JavaScript (without jQuery).
JavaScript:
var number = 1;
function IncrementNumber() {
document.getElementById('num').innerText = number;
number++;
}
HTML:
<span id="num">0</span>
<input type='button' onclick='IncrementNumber()' value='+'/>
Here is a jsfiddle with an example http://jsfiddle.net/G638z/

JSF Set CSS Style Using Javascript?

I have been looking with no success to see if I can dynamically apply a css style to JSF component or div using javascript. Is this possible.
This is pseudo code
<div style="myJSStyleFunction("#{myBean.value}")"> stuff </div>
And the function would return something like "position:relative;left:25px;"
I've had no luck and maybe it can't be done but would like a second opinion.
Edit:
I'm trying to see if I can keep a separation / reduce the coupling between the presentation/view and the model/controller. This is for indenting commenting or product reviews (to nest replies to comments or reviews). The most I really want to track is an integer on how deep a reply is. First level = 0 second level = 1, and so on. So a comment or product review would be 0 deep, a reply to the comment or review would be 1 and so on.
Then in the EL I wanted to call a javascript function and do something like
<script>
myJSStyleFunction(depth){
if(depth<=5){
var nest=20*depth;
var style="position:relative;left:" + nest + "px;";
return style;
}
}
</script>
And then then say for a third level comment (a reply to a reply) it would look like this:
<div style="position:relative;left:40px;"> stuff </div>
where
#{myBean.value}
evaluates to 2
I suspect like Daniel says I'll have to tightly couple the view but I'd rather not have to. I'd think there has to be a way. But maybe not.
I don't know where there are cleaner solutions for this. However this is one suggestion.
Assume your page looks like below and myBean.getValue() method returns an integer.
<h:form id="frm">
<div style="#{myBean.value}"> div1 </div>
<div style="#{myBean.value}"> div2 </div>
</h:form>
So you can do something like this at 'window.onload'.
<head>
<script>
window.onload = function() {
var childList = document.forms['frm'].childNodes;
for(var i = 0; i < childList.length; i++) {
if(childList[i].nodeName == 'DIV') {
var _div = childList[i];
var depth = _div.getAttribute('style');
_div.setAttribute('style', 'position:relative;left:' +(depth *20)+ 'px;');
}
}
}
</script>
</head>
Note: 1. In above sample code I assume all the DIVs inside the form should be indented.
2. For IE you may need to use _div.style.setAttribute('cssText','position:relative;left:' +(depth *20)+ 'px;')
3. Another solution for your question is using <script> tags immediately after your divs and putting the js part inside them. In this way you don't have to use fake styling style="#{myBean.value}" or window.onload event because you can directly call #{myBean.value} in your script.
I decided to skip the javascript approach and settled on a simpler and I think cleaner method to create the dynamic css classes for my situation. I already capture/calculate the depth value for each comment when it is entered. So I am just returning that value in EL and concatenating it to a 'base name' for the css class like so:
<div class="indent_#{(comment.commentDepth le 5) ? comment.commentDepth : 5}" >
comment comment blah blah blah
</div>
"indent_" is the base name for the css class. So for a 0 level comment it will have a class="indent_0". A reply to that comment will have class="indent_1".
I use the ternary so that if there are lot of replies under a given comment it doesn't indent right off the right hand side of the page. Even though you can keep going deeper, it will only indent up to 5 levels.
For my case at the moment, this is a simpler and cleaner method of adding some dynamically generated css class names. Right now I have to define 6 classes for this in the css file, but perhaps I'll figure out how to nest the boxes but it isn't a priority this works just fine for me for now.

Problem with JS, DOM and looping

I have a problem with JavaScript looping and DOM.
so I have a few div's, each has a background image defined by CSS, however when i rollover a text link, i wish for these background images to change, which ones will change depends on their class name and the link mouseover'ed
<div id="im1" class="web"></div>
<div id="im2" class="logo"></div>
<div id="im3" class="web"></div>
<div id="im4" class="logo"></div>
<div id="5" class="logo"></div>
web
so those are the divs with my link for the mouse over.
then to change these images i have some simple JavaScript, which works fine (if very long)....
function showweb() {
document.getElementById("im1").style.backgroundImage = "url('back/1col.png')";
document.getElementById("im2").style.backgroundImage = "url('back/2col.png')";
however, i wondered if there was a way i would condition by class name, and only change those with a certain class name, eg web, or logo. ive tried various ways and loops and things, but none seemed to work.
e.g
function showweb() {
for(i=0; i=5; i++){
url = "im" + i;
if(document.getElementById("url").className=="web"){
document.getElementById("url").style.backgroundImage = "url('back/"+ i +"col.png')";}
}
}
however this doesn't work, the divs just don't change..... am i doing something wrong? missing something? or doing it the completely wrong way?
all help appreciated, thanks in advance.
Edit: changed the "url" to url, my bad, that was very foolish, however still didnt work. i will try a few other ideas posted.
thanks everyone so far.
You don't need the quotes around url:
document.getElementById(url)
This may work (if the link to your images is right and presumed that by id="5" you mean id="im5". Play with it until it's right. Check your code thourougly, there were several errors (typos or worse 1) in your coding:
function showweb() {
for(var i=1; i < 6; i++){
var el = document.getElementById("im"+(i));
if(el && /web/.test( (el ||{}).className)){
el.style.backgroundImage = "url(back/"+ i +"col.png)";}
}
}
1 a few notes on that
id = "5" should supposedly be id ="im5"
i=0; i=5; i++ => i=5 should be i<5
i=0; i=5; i++ creates a global variable i. Use var i=0;...
given your id's, you should start with var i = 1
though not a real error, you don't need to surround the url value with apostrophes
to optimize call document.getElementById once and use it's result in the rest of the code
You're building the "url" variable, but then you pass the string constant "url" into the "getElementById()" function.
To get only elements of the desired class, you need node.getElementsByClassName('your_class'), where node can be document or some <div> selected by id, or any other node of the DOM tree.
Note: Remember that all methods that start with getElement will return single element, and those with getElements will return an array of elements, so this one returns an array which you need to iterate (even if there is only one element in it)
However, since you are working with DOM elements in JavaScript, you would save tons of time by using jQuery
You have a few of problem. First, you have quotes around the variable "url" so it's looking for an element with that id, which doesn't exist and thus fails when you attempt to access the className of a null lookup result. Second, your loop starts at 0, not one and you don't have a div with id "im0" so it would fail anyway when you attempt to get the className of that element, which also doesn't exist. Third, the check in your loop sets i to 5 instead of checking if it is less than or equal to 5. Your loop with thus continue forever, since 5 equates to true, which I'm sure is not what you want. Fourth, your code may break if you assign additional classes to the elements. Lastly, most of this sort of thing has already been done for you -- might I suggest you look into using a javascript framework, such as jQuery -- with the hover() method, as a better alternative than re-inventing the wheel if this isn't purely a learning exercise.

Categories

Resources