Add click events to php generated elements - javascript

I'm making a page that will generate a table of divs. Each row has a cell with a link. When that link is clicked a hidden div between the current row and the next will toggleSlide out.
The link will have id="clickLink_10" and the hidden div will have id="10" and class="hiddenDiv". The number 10 is a dynamic number generated form the id of the post in the database.
I have the animation working fine, as long as I hard code the numbers. But I want to connect the link to it's hidden div dynamically, since the rows will be fetched from a database.
Here's an example of how the html may look (it's more complicated in reality, but this is the key part):
<div>CLICK HERE</div>
<div class="hiddenDiv" id="11">blabla</div>
<div>CLICK HERE</div>
<div class="hiddenDiv" id="1">blabla</div>
<div>CLICK HERE</div>
<div class="hiddenDiv" id="3">blabla</div>
And here's what I'm trying to do in jQuery:
hiddenDivs = $('.hiddenDiv');
for(var i = 0; i < hiddenDivs.length; i++ ) {
$("#clickLink_" + hiddenDivs[i].id).click( function() {
$(hiddenDivs[i]).slideToggle(1000);
});
}
Which won't work obviously.I know I'm treating the i-variable wrong so view this a s dummy code. Very grateful for any help.

A valid option could be using data- attributes. I'll also change your numeric ids as only numbers is not a valid html id.
HTML
<div>CLICK HERE</div>
<div class="hiddenDiv" id="hidden_11">
<div>CLICK HERE</div>
<div class="hiddenDiv" id="hidden_1">
<div>CLICK HERE</div>
<div class="hiddenDiv" id="hidden_3">
JS
$(".clickLink").click( function() {
var hiddenDivId = "hidden_" + $(this).data("hidden-id");
$("#" + hiddenDivId ).slideToggle(1000);
});

You can use the ^= operator with an attribute selector to select elements. the ^= operator tells it to look for the attribute that "starts with" something, so:
$("a[id^=comment_]").click(function(e){
e.preventDefault();
var hideId = $(this).attr("id").replace("comment_","");
$("#"+hideId).slideToggle(1000);
});
So the selector a[id^=comment_] is basically saying select all anchor tags that have an id that start with comment_

Related

Get parent div id name when inner div clicked

I am struggling to find a way to get the name of the parent ID in a string. The code is part of a chat app written in Javascript and jQuery. Each time someone enters a message, the string outputs a block with username and text with a Close-x box before the username. When someone clicks the Close-x, it needs to grab the ID name of the parent div(json.innerdiv). The div with ID named json.outterdiv is the ID which allows me to delete the whole block message where as the json.innerdiv allows me to remove text, change text or just hide/show text. I tried searching on here for answers but all I ever get is undefined or null results.
My code:
var bubble = $('<div class="bubble-container" id="'+json.outterdiv+'"><span class="bubble"><div class="bubble-text" id="'+json.innerdiv+'"><p><div class="close-x" onclick="DelBubble(this)"></div>Some text</p></div></div>');
function DelBubble(clicked_id) {
alert($(this).parent().attr('id'));
}
Pass the event to onclick then get the closest of a class selector using jquery:
var bubble = `
<div class="bubble-container" id="2">
<span class="bubble">
<div class="bubble-text" id="3">
<p>
<div class="close-x" onclick="DelBubble(event)">
Close
</div>
Some text
</p>
</div>
</div>`;
$('body').append(bubble)
function DelBubble(e) {
const bubbleTextId = $(e.target).closest('.bubble-text').attr('id');
const bubbleContainerId = $(e.target).closest('.bubble-container').attr('id');
console.log({bubbleTextId,bubbleContainerId})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

AppendChild a element above a cerain element

So i have a div element which will be filled dynamically with others divs using the appendChild Method, this should display a list. The User is now able to sort that list with the JqueryUI Sortable option.I also added some sortable option attribues like follows:
Options:
$("#NameContainer").sortable("option", "axis", "y");
$("#NameContainer").sortable( "option", "containment", "parent" );
LIST
<div id="NameContainer" class="ui-widget">
<div id="Name_1">John</div>
<div id="Name_2">Jack</div>
<div id="Name_3">Charlie</div>
<div id="Name_4">Sawyer</div>
<div id="Name_5">Yin</div>
<div id="Name_6">Ben</div>
</div>
Now comes my problem. The appendChild always inserts the new div at the bottom of the container but i want to to add some space at the bottom of to the Container Div with a "br" or something like that. I want to add that space to make sure that when the user sorts the last item of that list it will get sorted correctly because the "containment" bounds sometimes wont allow to sort under the last item.
<div id="NameContainer" class="ui-widget">
<div id="Name_1">John</div>
<div id="Name_2">Jack</div>
<div id="Name_3">Charlie</div>
<div id="Name_4">Sawyer</div>
<div id="Name_5">Yin</div>
<div id="Name_6">Ben</div>
<br><!--SPACEHOLDER-->
</div>
So here comes my Question is there away to appendChild above a certain element? Like a "br" "div" or "p"?
Try this instead of appendChild:
Please note I have used random value to add in div as I don't have your dynamic value.
check fiddle: https://jsfiddle.net/dqx9nbcy/
<div id="NameContainer" class="ui-widget">
<div id="divspacer"></div>
</div>
<button id="btn">ADD Element</button>
$(document).ready(function(){
$("#btn").click(function(){
var parentnode = document.getElementById("NameContainer");
var existnode = document.getElementById("divspacer");
var rand = Math.floor((Math.random() * 10) + 1);
var newName = document.createElement("div");
newName.setAttribute("id", rand);
newName.setAttribute("value", rand);
newName.setAttribute("class","ui-widget-content");
newName.innerHTML = rand;
parentnode.insertBefore(newName,existnode);
});
});
refer http://api.jquery.com/appendto/ but you need to make sure that your are targeting right tag.
You can try with this code snippet.
HTML Snippet
<div id="NameContainer" class="ui-widget">
<div id="Name1">Name1</div>
<div id="Name2">Name2</div>
<div id="Name3">Name3</div>
<div id="Name4">Name4</div>
<br>
<br>
</div>
Javascript Snippet
$(document).ready(function(){
$("#btn").click(function(){
var containerDiv= $("#NameContainer");
var childList = containerDiv.children("div");
var newElementid = childList.length;
var newName = document.createElement("div");
newName.setAttribute("id", "Name"+(newElementid+1));
newName.setAttribute("value", "Name"+(newElementid+1));
newName.setAttribute("class","ui-widget-content");
newName.innerHTML = "Name"+(newElementid+1);
$(childList[childList.length-1]).after(newName);
});
});
This is specific to a situation where there are some elements in the initial list. The same can be modified for dynamic list of implementation by validating that childList.length is != 0 before using the same.

Having issue with DOM selection in jquery

<div class="wrapper">
<p class="text"></p>
</div>
<div class="wrapper">
<p class="text"></p>
<img></img>
</div>
<div class="wrapper">
<p class="text"></p>
<div class="vid"></div>
</div>
Assume above is a list of users' post, and I want to identify type of post of them. To select the image or video type is easy, for example the video, just select like $('.wrapper .vid').
But there is a problem when I want to select plaintext type of post, because the class text also appear in vid and image type of post.
Looks like you want wrapper elements which does not hae vid or img then
$('.wrapper').not(':has(img, .vid)')
If you want the text elements within them
$('.wrapper').not(':has(img, .vid)').find('.text')
You can use filter to get the three different types of posts. Something like this:
var $textPosts = $('.wrapper').filter(function() {
return $(this).find('img, .vid').length == 0;
});
var $imgPosts = $('.wrapper').filter(function() {
return $(this).find('img').length > 0;
});
var $vidPosts = $('.wrapper').filter(function() {
return $(this).find('.vid').length > 0;
});
Also note that the img HTML tag is self closing, eg:
<img src="foo.jpg" title="Foo" />
If i get this right that you want to get all the test in <p> with the class text, then you can do something like this
$('.wrapper > .text').html()
The above code will give you the content of only those element with class "text" that are direct under class "wrapper"
You can use .filter() to filter out the element with class text whose has no sibling:
var text = $('.text').filter(function() {
return $(this).siblings('*').length == 0
}).text();
Fiddle Demo
You can use
$('.wrapper p.text').text()
fiddle demo

Get variable from input and use it to change css classes

I have an input field with id="search".
<input id="search" type="text" />
Also there are few <div>'s that contains some text, like this:
<div id="textblock">Some text here</div>
<div id="textblock">Some other text here</div>
<div id="textblock">Few strokes</div>
<div id="textblock">More words</div>
I need to change style of a <div> (display:none) if that <div> had a text that user types in input field on the go.
For example, if value in the input would be "strokes", div (or divs) with word "strokes" disappears:
<div id="textblock">Some text here</div>
<div id="textblock">Some other text here</div>
<div id="textblock">More words</div>
I was looking for a jQuery solution, and I found some parts of code, but I can't put them together into one working piece. I know I should use keyUp() function, :contains() etc.
Firstly, id attributes must be unique - you may not have multiple elements with the same ID. Instead you should use a class attribute:
<div class="textblock">Some text here</div>
<div class="textblock">Some other text here</div>
<div class="textblock">Few strokes</div>
<div class="textblock">More words</div>
To then filter you can use jQuery's :contains() selector to determine which of your .textblock elements contain the text entered into your input element. For this I'm using a blur event handler which will trigger when the input element no longer has focus:
$('#search').on('blur', function() {
$('.textblock:contains(' + this.value + ')').hide();
});
JSFiddle demo.
If you want this to happen as soon as content is entered into the input element, we can use an input event handler instead and combine :contains() with jQuery's :not() selector to show elements which may have previously been hidden:
$('#search').on('input', function() {
$('.textblock:contains(' + this.value + ')').hide();
$('.textblock:not(:contains(' + this.value + '))').show();
});
JSFiddle demo.
As pointed out by Dreamonic in comments here, if you then want to handle the user removing the content from the input element, we need to ensure that we don't match the empty input against the .textblock contents. We can do this by using trim():
$('#search').on('input', function() {
if (this.value.trim().length > 0) {
$('.textblock:contains(' + this.value + ')').hide();
$('.textblock:not(:contains(' + this.value + '))').show();
}
else
$('.textblock').show();
});
JSFiddle demo.
Id's in your DOM should be unique. So changed your id's to classes for demo. Use .blur() and :contains(). Try this:
$("#search").blur(function(){
if($(this).val().length)
$("div.textblock:contains("+$(this).val()+")").hide();
else
$("div.textblock").show();
});
DEMO
$( "div" ).each(function( index ) {
if($( this ).text().contains($("#search").text()))
$(this).hide();
});
try above code on blur event of textbox

hide all but one element of certain class in Jquery

I am trying to create an effect whereby clicking on a title toggles the corresponding content div. Clicking on another title while some content is showing should hide that content div and show the content div corresponding to the title just clicked.
However the code is not doing anything, as you can see on the following jquery: http://jsfiddle.net/dPsrL/
Any ideas?
HTML:
<div class="row title">
<div class="title" industry_id="education">Ed</div>
<div class="title" industry_id="tech">Tech</div>
<div class="title" industry_id="finance">Fin</div>
</div>
<br>
<br>
<div class="row content">
<div class="content" id="education">Education is great</div>
<div class="content" id="tech">Technology is awesome</div>
<div class="content" id="finance">Finance is super</div>
</div>
JAVASCRIPT:
$(document).ready(function () {
$('.content').hide();
});
('.title').on('click', function () {
var clicked = $(this).attr('industry_id');
alert(clicked);
$("#"+clicked).toggle(400);
$("#"+clicked).siblings().hide();
});
Instead of toggling the clicked element first and then hiding the others, why don't you just hide everything first and then show the clicked one? Saves you a check, and all you have to do is switch the order
$('.title').on('click', function () {
var clicked = $(this).attr('industry_id');
alert(clicked);
$('.content').hide();
$('#' + clicked).show(400);
});
Your attribute doesn't have the id selector in it. You need to do a string concatenation :
$('.title').on('click', function () {
var clicked = $(this).attr('industry_id');
alert(clicked);
$('#' + clicked).toggle(400);
$('#' + clicked).siblings().hide();
//The two last lines could be :
//$('#' + clicked).toggle(400).siblings().hide();
});
Also you have to remove the class content and title on the row since it trigger the click event and the hide part.
Here's a working fiddle : http://jsfiddle.net/dPsrL/3/
Typo on ('.title'). Should be $('.title'). Also, you should probably not give the container divs the same class as the child divs and then use that same class in your CSS and jQuery. It just makes selection more difficult.
jsFiddle example

Categories

Resources