Jquery: Toggle closest parent element using .on("click")? [duplicate] - javascript

This question already has answers here:
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 9 years ago.
Given HTML such as
<div class="tpl grey">Hosts:
<p>Hi !</p>
<p>How are you ?</p>
<p>What ever.</p>
An other child & element type !
</div>
How to make that a click on a child element toggle the class="grey" of the closest parent .tpl element ?
The following code fails :
//Action to do on parent $(".tpl")
var switch1 = function () {
$(this).closest(".tpl").toggleClass("blue grey");
}
// On() click event
$(document).ready(function() {
$(".tpl").on("click", "p", switch1() );
});
Fiddle: http://jsfiddle.net/MRcCy/1

If you just want to toggle the closest .tpl (even though i only see one) try this
$(document).ready(function() {
$(".tpl p").click(function(){
$(this).closest('.tpl').toggleClass('grey');
});
});

Check this fiddle
$(document).ready(function() {
$(".tpl").click(function(){
$('.tpl').toggleClass('grey blue');
});
});

Related

How to select element by id which added using insertAfter? [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Attach event to dynamic elements in javascript
(15 answers)
Closed 6 months ago.
Using jquery I added an HTML button using insertAfter() now I would Like to select that button by id but didn't work.
$("button").click(function(){
$("<button id='new-button'>Added Button</button>").insertAfter("#this");
});
$("#new-button").click(function(){
$("<span> #new-button-work</span>").insertAfter("#this");
})
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button id="this">Insert span element after this element</button>
</body>
</html>
Because of new-button is inserted after script run so you can try this
$("button").click(function(){
$("<button id='new-button'>Added Button</button>").insertAfter("#this");
});
$("body").on("click", "#new-button", function(){ <--
$("<span> #new-button-work</span>").insertAfter("#this");
})
Because you're dynamically adding new elements to the DOM you should use event delegation - attaching listeners to a parent element (like document), and then using the 2nd argument of the on method to identify the element you want to match.
$(document).on('click', '#this', function() {
const button = '<button id="new-button">Added Button</button>';
$(button).insertAfter('#this');
});
$(document).on('click', '#new-button', function() {
const span = '<span> #new-button-work</span>';
$(span).insertAfter('#this');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="this">Insert span element after this element</button>

How to detect if new element is added in DOM? [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
I am trying to make a website, in which one makes a questions and there will be options for that questions.
I have a add option button, when user clicks the add option button, new option is added by this function.
function addOption(elem) {
elem = $(elem);
let ul = $(elem.parent().children()[1]);
let addedElem = $(
`<li class='ques-li'><input type='text' name='ques-option' class='ques-option' value='Option'><p class='remove-op'>X</p></li>`
);
addedElem.appendTo(ul);
}
let addOp = $('.ques-add');
$('.ques-add').click(function () {
addOption($(this));
});
This works well with one question, but when a user adds another question.
It is by this function.
let addQuestion = $('form button');
addQuestion.click(function () {
let quesBox = $('div.questions-box');
quesBox.html(quesBox.html() + `<div class='ques'>
<input type="text" name="ques-name" class="ques-name">
<ol class='ques-ul'>
<li class='ques-li'><input type="text" name='ques-option' class='ques-option'>
<p class='remove-op'>X</p>
</li>
<li class='ques-li'><input type="text" name='ques-option' class='ques-option'>
<p class='remove-op'>X</p>
</li>
</ol>
<p class='ques-add'>Add Another</p>
</div>`)
});
When i click the add Question button, it also works
but when i click the add option button on a newly created question,
it does not create a new option.
I noticed when i create a new question, it does not get the new option button.
So, i updated my code as follows :-
let addOp = $('.ques-add');
$(document).bind('DOMNodeInserted', function(){
addOp = $('.ques-add');
});
addOp.click(function () {
addOption($(this));
});
It also does not work.
I have no idea why this code is not working.
Thanks in advance.
Try using delegation approach that uses .on(). This will assure that the event will be attached to all the elements that are added to the document at a later time:
$('body').on('click', '.ques-add', function () {
addOption($(this));
});

How to change on click to toggle ? - hide element on unbind button [duplicate]

This question already has an answer here:
Jquery - Close dropdown/remove active class when clicking outside or clicking another dropdown
(1 answer)
Closed 4 years ago.
I get this code (it is not written by me)
Problem that I am not able to solve is:
To hide that iframe - I need to click the same button again and I would like to hide it on clicking somewhere else - something like toggle()
For now I tried to create new code with toggle, but I had problems with getting the right id, which is saved in clicked button id,
I also tried to base my new code on answer here :
.on() & toggle working together
and jQuery on('toggle') possible?
My code - It displays an iframe from a dynamically created link, when you click the button in the datatable column.
$("#example tbody").on("click", "a.actions", function() {
const id = $(this).attr('href');
let clicks = $(this).data('clicks');
if (clicks) {
$('#' + id).css("display", "none");
} else {
$('#' + id).css("display", "block");
}
$(this).data("clicks", !clicks);
let src = 'https://web02.datacentre.local/master-database/master-task-view-actions/entry/' + id;
$('#' + id).attr('src', src);
return false;
});
You can do this:
$(document).ready(function() {
$("button").click(function() {
$("div.d1").toggle();
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<button>Toggle</button>
<div class="d1" style="border:1px solid black;padding:10px;width:250px">
<p><b>This is a little poem: </b><br/> Twinkle, twinkle, little star<br/> How I wonder what you are<br/> Up above the world so high<br/> Like a diamond in the sky<br/> Twinkle, twinkle little star<br/> How I wonder what you are</p>
</div>

jQuery Click event not firing on element click [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
Below is my html and javascript. The Js is located in a app.js file and the html is a yes or no question. At the bottom of the javascript I have code that should fire on click events. Right now it is just to see if it detects a click on the p elements in the html but hasn't worked so far.
Can anyone detect why this event isnt taking place?
The other jQuery int he code does work but this jQuery isnt invoked by a function and is invoked based of strictly using a selector which leads me to believe there is something wrong with how I used document.ready in my project.
Html:
<div class="question animated slideInUp">
<h3>Do you know your individual monthly rent cost?</h3>
<div class="rentanswer">
<p>Yes</p><p>No</p>
</div>
<!--
<p>If not, we'll get the average rent of a zip code for you from Zillow</p>
<form onsubmit="Obj(this.p.name,this.p.value)">
<input type="number" id="p" name="rent" placeholder="Leave blank if N/A" >
<input id="s" type="submit" value="Submit">
</form>
-->
</div>
Javascript:
var quest = ['../partials/income.hbs', '../partials/state.hbs', '../partials/rent.hbs', '../partials/zip.hbs', '../partials/roomate.hbs', "../partials/summary.hbs"];
var iterator = 0;
//creates object that gets sent to api
function Obj(name, vale){
event.preventDefault(); //prevents pg refresh
$('.form').load(quest[iterator], function () {
$('.bar p#' + name).css("border","2px solid black").addClass('enter').next().css({"border":"2px solid black","pointer-events":"auto","cursor":"pointer"});
});
//loads next html question to page
if(name){
data[name] = vale;
}
//move array accessor up to next question
iterator++;
console.log(data);
}
var data = {};
//user can click already submitted values to load that orignal question and change it/
function redo(q, id) {
q = Number(q);
//if the current queston on the page is not the one being clicked we then change it to the one being clicked
if (q + 1 != iterator) {
$('.form').load(quest[q], function () {
$('#p').val(data[id]);
});
iterator = q + 1;
};
};
$(document).ready(function(){
$('.rentanswer p').on('click',function(){
console.log('hey');
});
});
Here you go with a solution https://jsfiddle.net/g8xt5g4y/
$(document).ready(function(){
$(document).on('click','.rentanswer p',function(){
console.log($(this).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Do you know your individual monthly rent cost?</h3>
<div class="rentanswer">
<p>Yes</p>
<p>No</p>
</div>
I believe your HTML is getting rendered dynamically, that's why your click method isn't working.
Try event delegate (mentioned in th above code).
Hope this will help you.

jQuery .click() not working in search suggestion [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
i want to create search suggestion. input type is created in this way:
<div class="signup_content_3">
<div class="signup_fieldName">
<p>
title
</p>
</div>
<div class="signup_text signup_input signup_search_parent" id="signup_flavorActor">
<input type="text" class="signup_searchType">
<div class="signup_suggestion">
</div>
</div>
my jQuery function to find key up is:
$('.signup_searchType').keyup(function(event){
$.ajax({url:"http://localhost:8000/auth/search/",success:function(result){
id=event.target.id;
var parent=event.target.parentElement.parentElement;
var add=parent.getElementsByClassName('signup_suggestion')[0];
add.style.display='block';
var child=add.firstChild;
while(add.firstChild){
add.removeChild(add.firstChild);
}
for(var i=0;i<Object.keys(result).length;i++){
var div=document.createElement('div');
div.innerHTML=result[i];
div.className='signup_oneSuggestion';
add.appendChild(div);
}
}})
});
and my jQuery click function is:
$('.signup_oneSuggestion').click(function(event){
console.log('click');
});
when i type in search type search suggestions appear but when i click on them does not print anything in console.
Use .on() (jQuery 1.7) with the element's ancestor, since it is created dynamically
$('.signup_suggestion').on('click', '.signup_oneSuggestion', function(event) {
console.log('click');
});
Dynamically created elements can be assigned an event in this way
$('body').on('click', '.signup_oneSuggestion', function(event) {
console.log('click');
});

Categories

Resources