$(".class").on('click', function () but not if it has $('class2') (child class) - javascript

I am working on a project where I need to have an onclick function for $(.playbox') but not if $('mp3buy') is pressed $(.mp3buy') is child of $('.playbox') so if I click $('mp3buy') its as if I click $(.playbox')
I have tried:
$(".playbox").not('mp3buy').on('click', function ()
and I also tried putting the following if statement within the function but then the function wont perform:
$(".playbox").on('click', function () {
if (this.hasClass('mp3buy')){
//do nothing
} else {
$(".playerbottom").removeClass("noclick");
$(".inlinethinger").removeClass("noclick");
var key = $(this).find(".play").attr('key');
var name = $(this).find(".play").attr('name');
window.nowplay = $(this).find(".play");// variable for now playing class .play
window.nowplay2 = $(this);
EvalSound(this, key);
$(".play").not(this).removeClass("pause");
$(".play").not(this).parent().parent().removeClass('playboxplaylight');
$(".play").not(this).parent().removeClass("greenback");
$(this).find(".play").toggleClass("pause");
$(this).find(".play").parent().parent().toggleClass('playboxplaylight');
$(this).find(".play").parent().toggleClass("greenback");
$(this).find(".play").hasClass("pause") ? $(".playerbottom").addClass("pausebottom") : $(".playerbottom").removeClass("pausebottom");
$(".nowplayingname").text(name);
$(".playerbottom").on('click', function () {
$(this).find(".play").hasClass("pausebottom") ? nowplay.addClass("pause") : nowplay.removeClass("pause");
});
}
});
I am wondering if there is a simple way to rule out a child class within an onclick function?

If I'm reading this right, you have this HTML structure:
<div class="playbox">
<div class="mp3buy">
... content ...
</div>
</div>
You can set a handler on .mp3buy and make use of event.stopPropagation().
$(".mp3buy").on("click", function(ev) {
ev.stopPropagation();
// Any clicks on .mp3buy will not be passed to .playbox's click handler.
});
$(".playbox").on("click", function() {
// Normal functionality here
});
$(".mp3buy").on("click", function(ev) {
ev.stopPropagation();
alert("mp3buy click handler called");
});
$(".playbox").on("click", function() {
alert("playbox click handler called");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="playbox">
.playbox content
<div class="mp3buy">
.mp3buy content
</div>
</div>

My proposal is to test the event target element against your class:
$(function () {
$(".playbox").on('click', function (e) {
if ($(e.target).is('.mp3buy')) {
// do nothing
return;
}
// do your stuff
alert('ok');
});
});
<script src="http://code.jquery.com/jquery-1.12.1.min.js"></script>
<div class="playbox" style="width: 300px;height: 300px;border:1px solid black;">
<button class="mp3buy" style="position:relative;top: 40%;left: 40%;">ClickMe</button>
</div>

Related

Removing an onclick event from a div with javascript

Basically what the title says this is the code that I've tried but it doesn't work:
<div id="box" onclick="doSmt(var1, bar2)">
if (condition){
box.removeEventListener("click" , doSmt)}
I think it's better if you remove the onclick event instead of that attempt
//onclick function
function doSmt(){
console.log("something");
}
//remove onclick event, this will be inside your if condition
document.getElementById('box').removeAttribute("onclick");
<div id="box" onclick="doSmt()"> div</div>
What what I read at MDN for removeEventListener you can't remove an event listener that is part of the HTML attribute. So there's two options:
Add the event listener on page load
onClickHandler = () => doSmt(var1, var2);
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('box').addEventListener('click', onClickHandler);
});
// and later
if (condition) {
document.getElementById('box').removeEventListener('click', onClickHandler)
Or if you can't modify the HTML you could modify doSMT to watch for a disabled bit.
let disableBox = false;
function doSmt() {
if (disableBox) return;
// ...
}
if (condition) {
disableBox = true;
}
Or
it can be removed by first accessing the element and then setting the attribute to null
<div id="myDiv" onclick="handleClick()">Click me</div>
<script>
function handleClick() {
alert("Div was clicked!");
}
// Remove the onclick event from the div
const div = document.getElementById("myDiv");
div.onclick = null;
</script>

How to override a parent event listener when a child element is clicked in Javascript?

How do I override aFunction inside of child.js?
I want the child event listener to trigger without aFunction triggering, and I can't modify parent.js.
Is this even possible?
index.html:
<th class="foo">foo
<span class="bar" data-feather="arrow-down"></span>
</th>
parent.js:
parent = {
init: function() {
parent.aFunction($('.foo'));
},
aFunction: function(element) {
element.on('click', function() {
alert('foo');
});
}, ...
window.onload = parent.init;
child.js:
$('.bar').on('click', function() {
alert('bar');
});
First its .bar cause no html tags called bar
event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Example
$('.foo').on('click', function() {
alert('foo');
});
$('.bar').on('click', function(e) {
e.stopPropagation();
alert('bar');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">foo
<span class="bar" data-feather="arrow-down">Bar</span>
</div>

single onclick function for buttons with a similar id pattern - JavaScript

I want to reduce the code.
function one() {
console.log("hai");
}
document.getElementById('dealsButton_1').onclick = one;
document.getElementById('dealsButton_2').onclick = one;
//I want the above 2 lines of code reduced to one.
A single function for on click on 'dealsButton_*' patterned id elements. How can I do this. The elements are dynamically loaded.
You can use querySelectorAll and the selector [id^=dealsButton_] to add the event listener in a single line - see demo below:
function one() {
console.log("hai");
}
Array.prototype.forEach.call(
document.querySelectorAll('[id^=dealsButton_]'), function(e) {
e.addEventListener('click', one);
});
<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>
If the markup is dynamically loaded you can base it on a static element like this:
function one() {
console.log("hai");
}
document.addEventListener('click', function(e) {
if (e.target && /^dealsButton_/.test(e.target.id))
one();
})
// dynamically add
document.body.innerHTML = `<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>`;
Are you looking for something like this:
function onClick(){
//single handler
}
$('[id*="dealsbutton_"]').click(onClick)
Here is a solution where you can choose ID name as u wish without a specific pattern of name.
<html>
<body>
<div id="abc">one</div>
<div id="def">two</div>
<script type="text/javascript">
function one() {
console.log("hai");
}
function addOnclickFunc (func, idArray){
idArray.forEach(function(element) {
document.getElementById(element).onclick = func;
})
}
addOnclickFunc(one,["abc","def"])
</script>
</body>
</html>
you use jQuery with regex for this
$.each( $("button[id^='dealsButton_']"), function () {
$(this).on('click', function(){
//code here
})
});
if want to make the function call names dynamically. pass it as data attribute to button element and call it using eval function
<button id="dealButton_1" data-click="one"></button>
$.each( $("button[id^='dealsButton_']"), function () {
$(this).on('click', function(){
var function_call = $(this).attr('data-click')
eval(function_call)
})
});

Getting the collection in a jQuery plugin

Basically, what I am trying to do is create a bbcode editor with a textbox, some buttons and jQuery. Here is my form:
<div class="form-group">
<div class="btn-group btn-group-sm">
<button type="button" class="btn glyphicon bbcode" rel="bold"><b>B</b></button>
<button type="button" class="btn glyphicon bbcode" rel="italic"><i>I</i></button>
</div>
</div>
<div class="form-group">
<textarea class="bbcode" rel="editor" cols="100" rows="12"></textarea>
</div>
and my plugin is called using:
<script>
$('document').ready(function() {
$('.bbcode').bbcode();
});
</script>
and the plugin itself, I am just trying to get the basics done at the minute to update the textbox data when a button is clicked:
(function($) {
"use strict";
$.fn.bbcode = function() {
this.click(function() {
var rel = $(this).attr('rel');
if (rel == 'editor') {
return this;
} else {
alert($(this).attr('rel')); // I can see this pop up so the click event is firing
$('.bbcode[rel=editor]').val('test');
return this;
}
});
}
} (jQuery));
This seems to be the only way I can pick up the textbox, I don't really want to hardcode the class I want like that. I think what I am looking for is a way to get the collection from the function call in the script tags.
This is more than likely something stupid/obvious I have overlooked.
The value of this in the immediate function refers to the collection. However, it is shadowed by the this inside your click handler (which refers to the element being clicked) so you cannot access it.
Create a variable to store this and that'll be your collection.
(function ($) {
"use strict";
$.fn.bbcode = function () {
var $editors = this;
this.click(function () {
var rel = $(this).attr('rel');
if (rel == 'editor') {
return this;
} else {
alert($(this).attr('rel')); // I can see this pop up so the click event is firing
$editors.val('test');
return this;
}
});
}
}(jQuery));

Override javascript click event one time

I would like to replace the default action of an click event for all anchors in a webpage.
When I use this piece of code:
<html> <head> <script>
var list=document.getElementsByTagName("a");
var isChecked = false;
function load () {
for (i=0; i<list.length; i++)
{
var old = (list[i].onclick) ? list[i].onclick : function () {};
list[i].onclick = function () {
if( !isChecked)
{
test();
old();
}
else
old();
};
}
}
function test() {
alert("new action");
isChecked = true;
}
</script> </head>
<body onload="load();">
<a id="nr_1" onClick="alert('test');"> Anchor 1 </A>
<a id="nr_2" onClick="alert('test2');"> Anchor 2 </A>
</body> </html>
When I click an anchor I get the alert out of the test function and then the default function of the second anchor (even when I click the first anchor). When I then again click one of the two anchors I always get the Alert from the second anchor.
How do I put the original onclick functions back for each anchor element? When someone has an solution in jquery I would be glad as well.
EDIT
I was succesfull using this code:
function load()
{
$('a').attr('disabled', 'disabled');
$('a').click(function(e){
if($(this).attr('disabled'))
{
alert("new");
e.preventDefault();
$('a').removeAttr("disabled");
this.click();
}
});
}
On loading of the page this function is called giving all anchor elements a "disabled" attribute. After clicking the element the e.preventDefault() function disables the inline onclick function. Then I remove the "disabled" attribute and call the click function of the element again. because now the element doesn't have a "disabled" attribute only the default function is performed. I'm still open for "more elegant" solutions to this problem, but for now I'm a happy camper!
If you use jQuery you can combine a one-time handler with a persistent handler:
Documentation for .one() and .on()
Working Example: http://jsfiddle.net/Q8gmN/
Sample HTML:
<input type="button" id="click" value="click" />
​
Sample JavaScript:
button.one('click', function () {
console.log('one time function fired');
});
button.on('click', function () {
console.log('persistent function fired');
});
​

Categories

Resources