I have a jquery click function calling 2 different ids, but I need to perform a peculiar code only for the id #go1.
How could it be done?
$('#go1, #go2').click(function(){
if ('#go1').click() {
//do what I need
}
});
Thank you
You need to use event target along with is selector to check whether target is element #go1:
$('#go1, #go2').click(function(e){
if ($(e.target).is('#go1')) { // or if (e.target.id == '#go1')
//do what I need
}
});
Related
I'm trying to write some Javascript to get click event on all elements with class from an array. Everything works fine, but I need it unclickable only until second condition in klikej() function is met. Once the click event fires, then the item with that class shouldn't be clickable. I've tried using removeEventListener and/or handle it with PreventDefaults(), but nothing works. I need to use only vanilla Javascript - no jQuery or anything else. Could you please help me?
poleRandomKaret.forEach(karta => {
document.querySelectorAll(`.${karta}`).forEach(element => {
element.addEventListener('click', event => {
console.log("klik");
klikej(event, element);
});
});
});
function klikej(event, element) {
let kliknuteKarty = document.querySelectorAll('[data-ovoce]');
if (kliknuteKarty.length < 2) {
element.setAttribute('data-ovoce', 'otoceno');
}
kliknuteKarty = document.querySelectorAll('[data-ovoce]');
if (kliknuteKarty.length === 2) {
kliknuteKarty[0].className === kliknuteKarty[1].className ? console.log("yes") : console.log("nope");
kliknuteKarty.forEach(element => {
element.removeAttribute("data-ovoce");
});
}
}
EDIT: The item shouldn't be clickable until the second condition in klikej() function is met. I'm trying to do memory game using vanilla JS. Function klikej() sets data attribute to an item and once there are two items with identical data attributes, it'll print in console "yes". If they're two different data attributes, they needs to be clickable again.
If you remove event listener, and will need to listen again, you would need to add it again or listen with something else. If I would need to recognize if something was clicked, I would add property to the element in the listener callback, so something like:
// before anything else we check if it was clicked before
if (element.clicked) {
// do your magic when element was already clicked
} else {
// do different magic with not yet opened element here
}
// after you did everything needed
// set the clicked attribute to true or false (if you need "unclick" it)
element.clicked = true;
It isn't directly answer to your question but hopefully another view to possible solution - if I understood you correctly, you do something when it was clicked and something else when it wasn't yet clicked and here you have control for both cases.
You can add an option called once as the third parameter of the addEventListener, which makes the event listener execute once.
element.addEventListener('click', function(e){
console.log('clicked'); // This will be executed once.
}, {once: true});
I want to check if a child-element of a clicked div has a certain class.
So i do this:
$('.panel').on('click', function (event) { if($(".panel input").hasClass('h5_validator_error')) { event.stopPropagation(); } });
The problem: I have more then one .panel class. Since my whole site gets generated by the user and json-files, i need a dynamic environment without ids.
So, actually my if-statement is preventing all .panel-clicks from doing their job.
I want to do something like this:
if($(event.target + ".panel input").hasClass('h5_validator_error')) { event.stopPropagation(); }
So i want to select all input - elements from the clicked div without
having an array and loop through it.
Is this possible? Or what is the most efficient way of selecting child-elements of the clicked one?
You should rather use this to get the targeted element:
$(this).find("input").hasClass('h5_validator_error');
or
$('input',this).hasClass('h5_validator_error');
You shoud make the dom object $(event.target) and then apply the jquery method on it.
Try this:
$('.panel').on('click', function (event) {
if($(event.target).find('input').hasClass('h5_validator_error')){
alert('true');
}
else{
alert('false');
}
});
Working Example
how can I target separately elements from a multitude of elements with the same classes or other properties. I cannot add different classes on each element so I need to target each element when I'm working on.
I have tried this so far but it is targeting all elements with input:text because my wrong condition of targeting each separately element working on.
var selector = $('input:radio').prop("checked", true);
var element = $ ('input:text');
$(selector).on('change', function( event ) {
if(this){
$(element).prop('disabled', true);
alert('disable only this element when radio is selected');
}
else{
alert('others input:text not disabled');
$('input:text').prop("disabled", false);
}
})
Fiddle:
By using DOM navigation method, you can do it really easily. Just use this :
var selector = $('input:radio').prop("checked", true);
var element = $ ('input:text');
$(selector).on('change', function( event ) {
var el = $(this).closest('.input-group').find('input:text');
element.prop('disabled', function(){
return !el.is(this);
})
});
Fiddle : http://jsfiddle.net/D2RLR/5874/
For dynamic input, you'll need to use Event delegation (read more here):
//document should be closest static element
$(document).on('change', 'input:radio', function(){
var el = $(this).closest('.input-group').find('input:text');
$('input:text').prop('disabled', function(){
return !el.is(this);
})
})
I don't understand exactly what you're trying to do, but you can use $(this) to target the element that triggered the event instead of trying to use a selector.
I think something like this is what you want:
$(selector).on('change', function( event ) {
$("input:text").prop("disabled", true);
$(this).parent().siblings("input:text").prop("disabled", false);
})
It disables all of the input:text and then enables the one whose radio button was selected.
Try this:
$(selector).on('change', function( event ) {
$('input:text').prop("disabled", false);
$(this).closest('.input-group').find(element).prop('disabled', true);
})
http://jsfiddle.net/D2RLR/5869/
Why not simplify?
Demo Fiddle
$('input:radio').on('change', function (event) {
$('input[type=text]').prop('disabled', false);
$(this).parent().next('input[type=text]').prop('disabled', 'false');
})
As others said, its not exactly clear what you're trying to do, or how general is your question. If the elements matching your selector have exactly the same attributes (including class), you may need to base on the context they are embedded on, or as a last resource, you may be able to base on the order of these elements.
Context: If you're looking for "p.many_like_me" , and you know the element you're trying to match is inside of #parent_id, you just refine your selector as "#parent_id p.many_like_me"
Order: If you know you're looking for the third element on the DOM matching your selector, you can use get() to select it: $("p.many_like_me").get(2) (get takes an index zero-based).
If you need to select them based on an event triggered by a nearby or somehow-related element, then some of the other answers given here are ok.
I have a div that will serve as container to other element, I have buttons that add element to that div.
Please see the demo for a get an idea about it.
So, what I want to do is to check before adding a new element is the div reached a maximum number of elements that I define, let's say 4.
I can check this condition before every add, but I am sure this is not the best way (we learned that if the code contains copy/paste then is not the best solution) Also, this is just a sample, in my case, I have many buttons..
Is there a way to have a listener like this?
$('#container').bind('divFull', function(){
//My code
});
So that I can disable buttons..
First, you have to listen to DOM change event, then you can trigger a custom event based on the number of children
$('#container').bind('DOMSubtreeModified', function(){
if($(this).children().length>=4){
$(this).trigger('divFull');
}
});
then you can bind to your custom divFull event
$('#container').bind('divFull', function(){
alert('container is full');
$('button').prop('disabled',true);
});
a working demo based on your example
I change a bit the #skafandri method because the event DOMSubtreeModified doesn't work on IE < 9 and it's depreciated.
The main change is to create a function which will call the divFull event if their is 4 children in the container.
var checkFull = function() {
if ($container.children().length === 4) {
$container.trigger('divFull');
}
}
$('#button1').click(function(){
$container.append('<div class="element">some text</div>');
checkFull();
});
Here is the demo.
my code and my problem is:
<script type="text/javascript">
$(document).ready(function() {
// this variable is used to set the dynamic elements
tagFlag = '';
$("#a1").click(function(event) {
event.preventDefault();
tagFlag = 'me'; // setting the element which I want to trigger later
});
$('#'+tagFlag).click(function(e) {
// do sthing here
});
});
</script>
</head>
<body>
make the element
<p id="me">some words here</p>
</body>
</html>
but.when I set the tagFlag,and click the "p" nothing is happen.BTW.there is error when tagFlag had been set nothing.So.How can I get what I want?
Thank you very much!!
Maybe you should look at the jQuery live() method that will assign event to all existing and future elements.
http://api.jquery.com/live/
There is no element wit the ID "a1". If you want the first anchor element use
$.("a:eq(0)")
instead.
If that's not it, report back please.
use a jquery object and add the clicked elements to it:
$(document).ready(function() {
$tagFlag = $("");
$("#a1").click(function(event) {
event.preventDefault();
$tagFlag.add($(this));
});
$tagFlag.click(function(e) {
// do sthing here
});
});
You can attach a .click() handler to document and check if the target of the click was the element you cared about, similar to how .live() behaves internally, like this:
$(function() {
var tagFlag = '';
$("#a1").click(function(event) {
event.preventDefault();
tagFlag = 'me';
});
$(document).click(function(e) {
if(tagFlag && //is it even set?
(e.target.id == tagFlag || $(e.target).closest('#'+tagFlag).length)) {
//do work here
}
});
});
You can give it a try here, the only change to your markup is the addition of a child element (to show click bubbling/handling working) and giving the anchor that a1 ID I think you intended for it to have in the question.
Alternatively if you know the set of elements that may be clicked, give them a class and bind a handler to them, checking the ID like I have above...or unbind the class and rebind to the specific ID each time, there's a few ways to go about this :)