I have a button with an onclick event as follows:
<button type="button" onclick="captions(event)">
<img src="someimg.png">
</button>
I need to be able to change the img src without using an ID to reference it. I want to pass "this" and the event (I need to do some other things that require event to be passed) but I cannot get this to work. Example of JS is below:
function captions(event) {
this.src = this.src.replace("img2.png");
}
Thanks!
I suggest not using inline event handlers. You should bind the event "unobtrusively" using JavaScript.
First give the button a class:
<button type="button" class="captions">
<img src="someimg.png">
</button>
Then bind the event:
window.onload = function(){
var captions = document.getElementsByClassName('captions');
for(var i = 0, len = captions.length; i < len; i++){
captions[i].addEventListener('click', function(event){
// this is your button, what you clicked on
// you need to get the image
var image = this.getElementsByTagName('img')[0];
// this.src.replace("img2.png") doesn't do what you think it does
// String.replace takes 2 parameters
image.src = '/your/new/image';
});
}
};
DEMO: http://jsfiddle.net/WcFzq/
You can get the element that was clicked using the event.target property (http://www.w3schools.com/jsref/event_target.asp).
function captions(event) {
event.target.src = "img2.png";
}
Here is a jsfiddle.
Following will solve your problem.
function captions(event) {
var img = this.childNodes[0];
img.src = img.src.replace("img2.png");
}
If you want to do an inline onclick event, you should simply be able to pass a new variable that captures the element into the function, like this:
function captions(element, event) {
. . . do stuff . . .
}
Then you would call it, passing this in for the element parameter, like this:
<button type="button" onclick="captions(this, event);">
<img src="someimg.png">
</button>
Related
Can some one help me?
The Idea is to create dynamic buttons with a loop and then use the jquery click function to use one of them
//I'm creating dynamic buttons like this:
for(i=0; i<1000; i++){
$contentBox.append('<button id="add'+ i +'" type="button" class="btn btn-success">Accept</button>');
//but how would I create the jquery click function?
$('#add'+i).click(function(e) {....});
//this does not create 1000 click functions. It only changes the id to the last one so what ever button you click on you will always get the las id
}
#Spencer's comment is on point - you can use a delegated event. Or, you can simply use the button class:
for(i=0; i<1000; i++){
$contentBox.append('<button id="add'+ i +'" type="button" class="btn btn-success">Accept</button>');
//Rest of your code
}
//Then attach the event to the class:
$('button.btn-success').click( function(){
//I suspect you'll want the ID so here goes
var buttonID = $(this).attr('id');
//The rest of the fun stuff
});
If you put i in the .... of your click handler, it won't fix its value to what it was when the click handler was created; rather it will always refer to the variable i which takes the value 1000 when you're done looping. Perhaps you could store i in an attribute of the button like below (or read it out of the element's id).
$contentBox = $('#content');
$result = $('#result');
for(i=0; i<10; i++){
$contentBox.append('<button id="add'+ i +'" data-eyeVal="' + i + '" type="button" class="btn btn-success">Accept</button>');
//but how would I create the jquery click function?
$('#add'+i).click(function(e) {$result.append('<br/>clicked ' + $(this).attr('data-eyeVal'))});
//this does not create 1000 click functions. It only changes the id to the last one so what ever button you click on you will always get the las id
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<div id="result"></div>
You should use live function for dynamic button click events. try this
$('#add'+i).live("click", function(){
// codings
});
project with these needs.
(10 points) When a button is clicked, the appropriate points are added to the total score.
(10 points) You are Not allowed to make any change to the HTML code provided above. In other words, you need to write unobtrusive JavaScript code, attaching event handlers in JavaScript rather than in HTML.
(10 points) The window.onload event handler should be an anonymous function.
(10 points) You should use the same event handler to handle the onclick event occurred on all of the four buttons on the webpage. In other words, you need to avoid code redundancy by using the this keyword.
I would like if someone could tell me a way I can use "this" in both of my functions so it doesn't have to be repetative like it is now in the first function, something like what I commented out. Or a way to simplify the code so it works as it does now.
<script>
window.onload = pageLoad();
function pageLoad() {
//this.onclick = okClick;
document.getElementById("6pt").onclick = okClick;
document.getElementById("3pt").onclick = okClick;
document.getElementById("2pt").onclick = okClick;
document.getElementById("1pt").onclick = okClick;
}
function okClick() {
var num1 = document.getElementById("score").value;
num1 = parseInt(num1);
var num2 = num1 + parseInt(this.id[0]);
document.getElementById("score").value = num2;
}
</script>
<body>
<div>
<input id="score" type="text" value="0" />
</div>
<div>
<button id="6pt">6 points (touchdown)</button>
<button id="3pt">3 points (field goal)</button>
<button id="2pt">2 points (safety/2-point conversion)</button>
<button id="1pt">1 point (extra point)</button>
</div>
</body>
Why don't you give all those elements a class, and then use
var myLinks = document.querySelectorAll('.myClass');
for(var i=0;i<myLinks.length;i++)
myLinks[i].onclick = okClick;
Inside okClick, the clicked element will be available via this (and also event.target).
Event handlers, like onclick are called in the context of the target object, thus you can safely use this within any event handler function. This also applies to jQuery attached events.
The above is valid for the 'okClick' function. You asked about "both of my functions", so if you're referring to pageLoad, that function is not executed in the context of an object, so you can't use this. But why would you need it? It won't help you much.
You can use the bind function which will give a given context to your function:
var context = window;
context.something = 5;
var myFunc = function () {
console.log(this.something); //5
}.bind(context);
If all you want to do is attach the same okClick() to each button then you should try and use a more general selector than ID. You can only have one ID per element so, like you've noticed, you must individually hook into each one.
Instead, try a more general selector, like document.getElementsByClassName("className");, which would be a bit more general:
<body>
<div>
<input id="score" type="text" value="0" />
</div>
<div>
<button id="6pt" class="score-button">6 points (touchdown)</button>
<button id="3pt" class="score-button">3 points (field goal)</button>
<button id="2pt" class="score-button">2 points (safety/2-point conversion)</button>
<button id="1pt" class="score-button">1 point (extra point)</button>
</div>
<script>
(function(){
// Same as yours
function okClick() { ... }
var buttons = document.getElementsByClassName("score-button");
for(var i = 0, len = buttons.length; i < len; i++)
{
buttons[i].onClick = okClick;
}
}).call(this);
</script>
</body>
There's fancier selectors available in either jQuery or more modern javascript implementations which will save you having to use a class selector, you'll have to read into that though - or see Sidd's answer, which is doing exactly that (it's cleaner).
When I click on the link it's working perfectly but only ONCE.
I want to be able to be able to keep the addEventListener even after it's been executed.
<div id=myBox>
append
</div>
document.getElementById("append").addEventListener("click", appendMore);
function appendMore() {
myBox.innerHTML += '1';
}
You'll want to use a separate element to insert your content into.
document.getElementById("append").addEventListener("click", appendMore);
function appendMore() {
tgt.innerHTML += "1";
}
<div id=myBox>
append
<span id="tgt"></span>
</div>
// Parent element
var el = document.querySelector('#myBox');
// Find append and add listener
el.querySelector("#append").addEventListener("click",appendMore);
function appendMore( event ) {
// Append new text node
el.appendChild( document.createTextNode('1') );
}
It would be achieved easily by using jQuery.
$('#append').click(function () {
$('#myBox').append('1');
});
find this JSFIDDLE
NB: Please let us know if you want to achieve this using just plain javascript.
How do I make a DIV degradable by the use of an image.
This is my code:
var tDV = 0;
$("#aTx").click(function() {
var diagonalScl;
var txSiz;
tDV++;
$("#ltn").append('<div id="aTextDV'+tDV+'></div>');
$("#aTextDV"+tDV)
.append('<div class="txmoPos" id="mvTx" onclick="mTxt(\'aTextDV'+tDV+'\')"><img src="img/img1.png"/></div>')
});
function mTxt(mndM){
$("#"+mndM).draggable();
}
There is quote error in your onclick attribute value,
It should be like this
$("#aTextDV"+tDV).append("<div class='txmoPos' id='mvTx' onclick='mTxt(\"aTextDV"+tDV+"\")'><img src=''/></div>")
Check the Working Demo Here
I have to pass innerHTML to a div using my JavaScript function.The innerHTML that I am passing also has a div for which I have to attach a click event so that on click of it, the element responds to the click event.
I have a fiddle here to explain the problem:
http://jsfiddle.net/K2aQT/2/
HTML
<body>
<div id="containerFrame">
</div>
</body>
JavaScript
window.onload = function(){usersFunction();};
function usersFunction(){
var someHtml = '<div> <div class ="btnSettings"> </div> <span></span> </div>';
changeSource(someHtml);
}
function changeSource(newSource){
document.getElementById("containerFrame").innerHTML = newSource;
}
While passing the source, how do I tell JavaScript function that this HTML being passed also has some element which has to be bound to a click event?
If you have to do it this way, you could consider adding the click handler inside the HTML string itself:
var someHtml = '<div> <div class ="btnSettings" onclick="return myFunction()"> </div> <span></span> </div>';
Alternatively, after modifying the .innerHTML, find the right <div>:
var frame = document.getElementById('containerFrame');
frame.innerHTML = newSource;
var settings = frame.getElementsByClassName('btnSettings')[0];
// depends on the browser, some IE versions use attachEvent()
settings.addEventListener('click', function(event) {
}, false);
i think you need something like that:
document.getElementById("containerFrame").onclick = function() {
// put your function here
};