Remove onclick event from img tag - javascript

Heres my code:
<div id="cmdt_1_1d" class="dt_state1" onclick="sel_test(this.id)">
<img id="cmdt_1_1i" onclick="dropit('cmdt_1_1');" src="/site/hitechpackaging/images/items/bags_menu.jpg ">
<span class="dt_link">
BAGS
</span>
</div>
Unfortunately I cannot modify this file, is there a way using javascript to disable the onclick from the img tag only.
I was using this script but it disable the onclick event from all images. But i want only from this component
var anchorElements = document.getElementsByTagName('img');
// for (var i in anchorElements)
// anchorElements[i].onclick = function() {
// alert(this.id);
// return false;
// }
Any ideas will be appreciated.
Edited:
Is there a way to stop the function dropit from executing, is it possible using javascript. On page load, etc.
another option is can i rename the img file using javascript??

document.getElementById('cmdt_1_1i').removeAttribute("onclick");

var eles = document.getElementById('cmdt_1_1d').getElementsByTagName('img');
for (var i=0; i < eles.length; i++)
eles[i].onclick = function() {
return false;
}

Lots of answers, but the simplest is:
document.getElementById('cmdt_1_1i').onclick = '';

try something like this:
var badImage = document.getElementById("cmdt_1_1i");
badImage.onclick = null;
badImage.addEventlistener("click",function(e){
e.preventDefault();
e.stopPropagation();
return null;
},true);

If you later need to restore the onclick property, you can save it in a field before overwriting it:
document.getElementById(id).saved=document.getElementById(id).onclick;
document.getElementById(id).onclick = '';
so that later you can restore it:
document.getElementById(id).onclick=document.getElementById(id).saved;
This can be useful especially in the case, in which the original onclick property contained some dynamically computed value.

You can programmatically reassign event listeners. So in this case, it might look something like:
const images = document.querySelectorAll('#cmdt_1_1d img')
for (let i = 0; i < images.length; i++) {
images[i].onclick = function() => {}
}
...where the query above returns all of the img tags that are descendants of the element with ID cmdt_1_1d, and reassigns each of their onclick listeners to an empty function. Therefore no actions will take place when those images are clicked.

Related

".addEventListener is not a function" why does this error occur?

I’m getting an ".addEventListener is not a function" error. I am stuck on this:
var comment = document.getElementsByClassName("button");
function showComment() {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);
<input type="button" class="button" value="1">
<input type="button" class="button" value="2">
<div id="textfield">
</div>
The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment is an empty array.
So you should move your script after the html element is available.
Also, getElementsByClassName returns html collection, so if you need to add event Listener to an element, you will need to do something like following
comment[0].addEventListener('click' , showComment , false ) ;
If you want to add event listener to all the elements, then you will need to loop through them
for (var i = 0 ; i < comment.length; i++) {
comment[i].addEventListener('click' , showComment , false ) ;
}
document.getElementsByClassName returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0]; should get you what you want.
Update #1:
var comments = document.getElementsByClassName('button');
var numComments = comments.length;
function showComment() {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
for (var i = 0; i < numComments; i++) {
comments[i].addEventListener('click', showComment, false);
}
Update #2: (with removeEventListener incorporated as well)
var comments = document.getElementsByClassName('button');
var numComments = comments.length;
function showComment(e) {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
for (var i = 0; i < numComments; i++) {
comments[i].removeEventListener('click', showComment, false);
}
}
for (var i = 0; i < numComments; i++) {
comments[i].addEventListener('click', showComment, false);
}
var comment = document.getElementsByClassName("button");
function showComment() {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
for (var i in comment) {
comment[i].onclick = function() {
showComment();
};
}
<input type="button" class="button" value="1">
<input type="button" class="button" value="2">
<div id="textfield"></div>
The first line of your code returns an array and assigns it to the var comment, when what you want is an element assigned to the var comment...
var comment = document.getElementsByClassName("button");
So you are trying to use the method addEventListener() on the array when you need to use the method addEventListener() on the actual element within the array. You need to return an element not an array by accessing the element within the array so the var comment itself is assigned an element not an array.
Change...
var comment = document.getElementsByClassName("button");
to...
var comment = document.getElementsByClassName("button")[0];
Another important thing you need to note with ".addEventListener is not a function" error is that the error might be coming a result of assigning it a wrong object eg consider
let myImages = ['images/pic1.jpg','images/pic2.jpg','images/pic3.jpg','images/pic4.jpg','images/pic5.jpg'];
let i = 0;
while(i < myImages.length){
const newImage = document.createElement('img');
newImage.setAttribute('src',myImages[i]);
thumbBar.appendChild(newImage);
//Code just below will bring the said error
myImages[i].addEventListener('click',fullImage);
//Code just below execute properly
newImage.addEventListener('click',fullImage);
i++;
}
In the code Above I am basically assigning images to a div element in my html dynamically using javascript. I've done this by writing the images in an array and looping them through a while loop and adding all of them to the div element.
I've then added a click event listener for all images.
The code "myImages[i].addEventListener('click',fullImage);" will give you an error of "addEventListener is not a function" because I am chaining an addEventListener to an array object which does not have the addEventListener() function.
However for the code "newImage.addEventListener('click',fullImage);" it executes properly because the newImage object has access the function addEventListener() while the array object does not.
For more clarification follow the link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function
The main reason of this error is this line
document.getElementsByClassName("button")
Cause the getElementsByClassName returns an array-like object of all child elements or a collection of elements.
There are two possible solutions AFAIK -
Treat the variable containing document.getElementsByClassName("button") as an array and be specific when using an event listener.
Example -
comment[0].addEventListener('click' , showComment , false )
Use id for selecting that specific element.
Example-
document.getElementById('button')
Try this one:
var comment = document.querySelector("button");
function showComment() {
var place = document.querySelector('#textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);
Use querySelector instead of className
<script src="main.js" defer></script>
which makes execute your code after the document fully loaded hence the javascript has complete reference

Assigning .on() - keyup to dynamically created elements

The idea of this script is to allow dynamically created elements to respond to a keyup function that changes the inner html (or jQuery text()) based on what is inside of a text form.
Each dynamically created element has it's own text form and title. So whatever you type in that given element's text form should become the title for that element which is wrapped in tags.
I've tried a few ways but I just cant get it to work. What is the best way to go about this?
Here's my latest attempt - http://jsfiddle.net/gnkxxgjz/1/
$('body').on('keyup', '.qForms', function() {
var nameOfLoan = [];
var loanOfName = function(t) {
if ($(this).hasClass('.loanNameV'+t)) {
$('body').on('keyup', '.qForms', function() {
var loanN = $('.loanNameV'+t).val();
$('.nameLoan'+t).text(loanN);
});
}
else {
return false;
}
};
for (var t=1; t < z; t++) {
nameOfLoan[t] = loanOfName(t);
}
for (var j=1; j < z; j++) {
nameOfLoan[j]();
}
});
Take a look at this Fiddle
<button onclick="crea()">create</button>
<div id="d1">
</div>
function crea(){
$('#d1').append( $("<h2></h2><input>").on('keyup',function(){
$(this).prev().html( $(this).val() );
}) )
}
Something along these lines:
$(document).on("keypress", $("input"), function(e){
console.log($(e.target).attr("id"))
});
This will print to the console the id attribute of any input field you type into. Please provide how the input and text elements are related and I might be able to link them in this code piece.

Can you use "this" attribute on onclick of an HTML tag?

Can you use the this tag for the onclick on an HTML tag?
Here's my JS code...
function changeImage() {
this/*<-- right there <--*/.src=a;
}
document.getElementsByTagName('img').onclick = function(){
changeImage();
} ;
Am I doing something wrong?
Use it this way...
function changeImage(curr) {
console.log(curr.src);
}
document.getElementsByTagName('img').onclick = function(){
changeImage(this);
} ;
You could use the .call() method to invoke the function with the context of this.
In this case, you would use:
changeImage.call(this)
Example Here
function changeImage() {
this.src = 'http://placehold.it/200/f00';
}
document.getElementsByTagName('img')[0].onclick = function(){
changeImage.call(this);
};
As a side note, getElementsByTagName returns a live HTMLCollection of elements. You need to apply the onclick handler to an element within that collection.
If you want to apply the event listener to the collection of elements, you iterate through them and add event listeners like this:
Updated Example
function changeImage() {
this.src = 'http://placehold.it/200/f00';
}
Array.prototype.forEach.call(document.getElementsByTagName('img'), function(el, i) {
el.addEventListener('click', changeImage);
});
Or you could simplify it:
Example Here
Array.prototype.forEach.call(document.getElementsByTagName('img'), function(el, i) {
el.addEventListener('click', function () {
this.src = 'http://placehold.it/200/f00';
});
});
You are doing two things wrong.
You are assigning the event handler to a NodeList instead of to an element (or set of elements)
You are calling changeImage without any context (so this will be undefined or window depending on if you are in strict mode or now).
A fixed version would look like this:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].onclick = function () {
changeImage.call(this);
};
}
But a tidier version would skip the anonymous function that does nothing except call another function:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].onclick = changeImage;
}
And modern code would use addEventListener.
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].addEventListener('click', changeImage);
}
However, images are not interactive controls. You can't (by default) focus them, so this approach would make them inaccessible to people who didn't use a pointing device. Better to use controls that are designed for interaction in the first place.
Generally, this should be a plain button. You can use CSS to remove the default padding / border / background.
If you can't put a button in your plain HTML, you can add it with JS.
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
var image = images[i];
var button = document.createElement('button');
button.type = "button";
image.parentNode.replaceChild(button, image);
button.appendChild(image);
button.addEventListener('click', changeImage);
}
function changeImage(event) {
this.firstChild.src = a;
}

Reset the html element using jquery

I am having a div with lot of elements inside the div. For some scenario i want to reset the value for the div's element to the initial status.
Is there any way to do this??
if($(window).width()<=960){
$('#desktopCart').html(/i want to reset this element/);
}
if($(window).width()>960){
$('#mobileCart').html("/i want to reset this element/");
}
try:
$( document ).ready(function() {
var initialValue =$('#mobileCart').html();
});
if($(window).width()<=960){
$('#desktopCart').html(initialValue);
}
if($(window).width()>960){
$('#mobileCart').html(initialValue);
}
use .empty() of jquery
$("#divId").empty();
It will remove all the child elements and text in that particular element.
If you want to restore the initial state of the div, you should save the initial innerHtml to a variable a document.ready().
Like,
var desktopCart;
var mobileCart;
$(document).ready(function(){
desktopCart=$('#desktopCart').html();
mobileCart=$('#mobileCart').html();
});
Then restore the html whenever you want,
if($(window).width()<=960){
$('#desktopCart').html(desktopCart);
}
if($(window).width()>960){
$('#mobileCart').html(mobileCart);
}
First clone the element instead of saving the content. Then use replaceWith to restore it.
$(document).ready(function() {
var divClone = $("#mobileCart").clone();
if($(window).width()<=960){
$('#desktopCart').html(/i want to reset this element/);
}
if($(window).width()>960){
$("#mobileCart").replaceWith(divClone);
}
});
For further reference, please see the below link.
How can I "reset" <div> to its original state after it has been modified by JavaScript?
What if I have multiple elements ? And want to save the elements' state at regular intervals ? And regularly reset them ? There might not be just one of them .... maybe I will have a and p and div and too many of them. But I want to reduce typing ? What do I do ?
I am glad you asked.
// Write Once: Use Anywhere functions
$.fn.reset = function () {
var list = $(this); // list of elements
for(var i = 0, len = list.length; i < len; i++){
list.eq(i).text(list.eq(i).data("initValue"));
}
};
$.fn.saveState = function () {
var list = $(this); // list of elements
for(var i = 0, len = list.length; i < len; i++){
list.eq(i).data("initValue", list.eq(i).text());
}
}
$("div").saveState(); // simple call to save state instantly !
// value change!
$("div:nth-child(2)").text("99999");
$(window).resize(function () {
if ($(window).width() <= 960) {
$("div").reset(); // simple call to reset state instantly !
}
});
DEMO Resize window

Detect clicks of images inside iframe

I cant figure out why this isn't working. It's probably something simple. The iframe is from the same domain as parent page.
I know I can use jQuery, but I want to learn to do it in pure JavaScript.
My code so far:
document.getElementById('my_iframe').onload = function() {
document.getElementById('my_iframe').contentWindow.document.getElementsByTagName('img').onclick = function() {
alert("image in iframe was clicked");
}
}
Forget the frame business for a second, and look at this code:
document.getElementsByTagName('img').onclick = function() {
Will that ever work? No. You are getting an object (a NodeList, to be precise) containing all the img elements in the document. You are adding an onclick property to that object. Not to the elements themselves: to an object that points to them. The function will never be fired because it is never applied to any elements.
You should do exactly the same as you normally would: loop though all the images you've found and apply the function to them individually.
var onclickFn = function() {
alert("image in iframe was clicked");
},
images = document.getElementById('my_iframe').contentWindow.document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].onclick = onclickFn;
}
document.getElementsByTagName is returning a collection of images. You can't just set a click handler on the entire collection. You need to loop through them one at a time.
var allimgs = document.getElementById('my_iframe').contentWindow.document.getElementsByTagName('img');
for (var i = 0; i < allimgs.length; i++) {
allimgs[i].onclick = function() {
alert("image in iframe was clicked");
};
}

Categories