Write click event dynamically on jquery - javascript

Here is the original html
<div class='cl_{{ $gen }}'>{{$gen->name}}</div>
<div class='jl_{{ $var }}'>{{$gen->name}}</div>
After looping over here is the html i got as output
I wanted to do if i click on the class cl_x, then the jl_x should be visible and other should be hidden and by default the first cl_1 should be visible. How can i do this ?
<div class='cl_1'>One</div>
<div class='cl_5'>Two</div>
<div class='cl_6'>Three</div>
<br>
<div class='jl_1'>Alpha</div>
<div class='jl_1'>Andrew</div>
<div class='jl_1'>Christ</div>
<div class='jl_5'>Anto</div>
<div class='jl_5'>Brito</div>
<div class='jl_6'>Oyster</div>
<div class='jl_6'>Beta</div>
Note : All the 1,5,6 are not standard as they are coming from database.
I really can't able to think how to achieve this. Help pls
But Here is what i have tried the logic
Inside Document Ready
Loop over the jquery like html
Write click event to show hide if they cick on cl_*
Trigger the click event for first occurance.
Don't worry about the html generated but the need is to write the jquery events dynamically or something else
But can't able to implement the code pls help
Script :
$(document).ready(function() {
//not sure whether i should loop over the jquery itself or write anything like the element starts with cl-* like that
});
Update :
Here is the Fiddle i have so far

You don't really want to use class for this - a custom data attribute makes sense, though. Like <div class="cl" data-number="{{ $gen }}"> with <div class="jl" data-number="{{$var}}"> on the other elements.
Then inside the $(document).ready(...) you can do something like:
$('.jl').hide().first().show();
$('.cl').click(function(){
$('.jl').hide().filter('[data-number="' + $(this).data('number') + '"]').show();
})
It would also be good to make up more meaningful names than "cl" and "jl" - classes should generally be semantic.

Would move the unique identifiers to a different attribute and add a common class to all the J group
<div class='cl' data-gen="{{ $gen }}">{{$gen->name}}</div>
<div class='jl jl_{{ $var }}'>{{$gen->name}}</div>
JS
$(document).on('click','.cl',function(){
$('.jl').hide().filter('.jl_' + $(this).data('gen') ).show();
})

Add a base "jl" class to all your html that has anything with a "jl_*" so that you will have access to anything overall that has the "jl" class then toggle it hidden or not hidden like so:
HTML:
<div class='cl {{ $gen }}'>{{$gen->name}}</div>
<div class='jl {{ $var }}'>{{$gen->name}}</div>
JS:
$(document).on('click', '.cl', function(e){
var classes = ($(e.target).attr("class").split(' '));
$('.jl').toggleClass("hide");
$('.jl' + "."+ classes[1]).toggleClass("hide");
});
Style:
.hide{
display: none;
}
https://jsfiddle.net/rc368gjp/

Related

How to print the content of a div that changes based on a foreach statement?

I have an ArrayList named conversations_client, I want to be able to get the value of conversation[6] for each div.
Each one the the media div represent a conversation.
Here is a part of my code :
<c:forEach var="conversation" items="${conversations_client}" >
<div class="media">
<div class="media-left">
<input class="checkbox" type="checkbox" name="selected-conv">
</div>
<div class="media-body">
<h4 class="media-heading">${conversation[0]}</h4>
<span class="hidden">${conversation[6]}</span>
......
I had first tried to use this code :
<script type="text/javascript">
$('.media').click(function(){
var text = $(this).text();
alert(text);
});
</script>
But it would print not only conversation[6] but others as well since they're all inside the div with class media.
Then I tried this :
<script type="text/javascript">
$('.media').click(function(){
var text = $('.hidden').text();
alert(text);
});
</script>
But it would print the same id for all divs, which is the id of the first one.
How can I do that? and would it be better to wrap those media divs with tags to be able to use a specific action for each one of them? because I am displaying all conversations, then once the user will click on one them I'll have to recover its id to be able to display the messages of that specific conversation and it isn't advisable to write Java code inside of jsp.
Thank you :)
Use find from current element.
$('.media').click(function()
{
var text = $(this).find('#hidden').text();
alert(text);
});
UPDATE:
You are using loop to repeat the markup. It's not good to use ID hidden multiple times as per W3C standards. ID should be unique and should be used once in the page.
Use class instead of id for multiple usages. In this case class="hidden"
Better change <span id="hidden">${conversation[6]}</span> to <span class="hidden">${conversation[6]}</span>
Also change JS to find .hidden
$('.media').click(function()
{
var text = $(this).find('.hidden').text();
alert(text);
});

Making a Div Dynamically using javascript/Jquery

I have following HTML code for a DIv, i was wondering if there is way i can make same div programaticaly using Javascript / Jquery.
Or is there a way i can append div having class "panel panel-default" in div having ID accordion it as first element every time.
Thanks for help
you can Use .prepend() or .prependTo().
prepend() puts the prepending elem at first index
$('#accordion').prepend("<div> this is new div</div>");
Since you wanted to copy html each time in a click. you Should use unique id(#appendpanel is duplicating each time) and use clone().For avoiding duplicate you can try this(use class name instead id)
avoid copy id demo
sample live demo
You need to change the markup to add some ids
<a id="clone">Add</a>
then
<div style="display:none" id="addme">...</div>
then
jQuery(function ($) {
var $cp = $('#addme');
$('#clone').click(function(){
$cp.children().clone().prependTo('#accordion')
})
});
Demo: Fiddle
Aside from using the createElement and assigning all of the attributes and adding them in the correct hierarchical order, there are a couple ways to do this.
1) enclose the elements as text and use $.parseHTML( htmlString ) to return a DOM node.(this is jquery)
2) paste the html inside a <script> tag with it's type set to something like type="html". The benefit of this is that if the script has an id, you can reference it via document.getElementById("idOfScriptTag"). The browser won't parse the contents of the script tag if it doesn't recognize its type, so you can just leave it on the page until you need it.
If I understand you correctly you want to add some html code through javaScript/jquery at a paticular poisitionin the DOM.You can do it in the following way
$(".some_class_of_div" ).html(
'<div class="class1" style="position:absolute; width:25px !important; display:none;">\
<img class="class2" src="http://xylz.com/static/img/black.png" style="width:30px;height:17px;padding-left: 10px;display:none;" title="try by click" >\
<div class="class3" style="position:absolute; width:25px !important; padding-left: 10px;display:none;">\
<img class="class4" src="http://xylz.com/static/img/border.png" style="width:20px;">\
<div class="class5" style="position:absolute; width:25px !important;display:none;">\
<img class="class6" src="http://xylz.com/static/img/settings.png" style="width:20px;">\
</div>\
</div>\
</div>\
<form class="class7" method="get" style="display:none;" accept-charset="utf-8">\
<input name="some_id" type="hidden" value="1">\
</form>');
Here I have used a class of div and added some html to it.The html can be anything you want.Instead of class you can also use id.hope that helps.

Using jQuery 'this' with a selector of multiple elements

Sorry jQuery noob question here, I am attempting to make all of the div elements with the class .thumbnail clickable with a callback function. But, once one of the div(s) of that class is clicked I need the specific ID of that given div so I can do further manipulation to that specific one. I am confused if I would use 'this' to reference that specific div once it is clicked or if I am looking at this the wrong way.
Im sure this is a very simple question for you jQuery gurus to answer, its been a long day and my brain is completely zombified.
Example Sudo Code:
<script>
$(document).ready(function() {
$(".thumbnail").click(function() {
//need to get id of thumbnail that was clicked, this is where I am confused
var thumbnail_id = $(this).attr('id')
alert(thumbnail_id);
});
});
</script>
<div class=thumbnail" id="1">Tom</div>
<div class=thumbnail" id="2">Jerry</div>
<div class=thumbnail" id="3">Sue</div>
<div class=thumbnail" id="4">Mary</div>
<div class=thumbnail" id="5">Brian</div>
DOnt you think thumbnail should be written like "thumbnail" and not thumbnail"
It is unclear what your jQuery problem is. To address the question you're asking, when an object is clicked in your code, the click handler will be called and this will be set to the DOM element that was clicked on. This works if there is one object with the thumbnail class or many.
If your problem is really that your HTML is in error, then you should add the missing quote to change this:
<div class=thumbnail" ...
to this:
<div class="thumbnail" ...
FYI, a better way to do this is as follows. This fixes the quote problem and uses a data attribute rather than a numeric id value:
Working demo: http://jsfiddle.net/jfriend00/8tczB/
<script>
$(document).ready(function() {
$(".thumbnail").click(function() {
//need to get id of thumbnail that was clicked, this is where I am confused
var thumbnail_id = $(this).data('id');
alert(thumbnail_id);
});
});
</script>
<div class="thumbnail" data-id="1">Tom</div>
<div class="thumbnail" data-id="2">Jerry</div>
<div class="thumbnail" data-id="3">Sue</div>
<div class="thumbnail" data-id="4">Mary</div>
<div class="thumbnail" data-id="5">Brian</div>

How to get a value from div without write some event (onclick,etc) using jquery

I have some question about how to get some value from some element like div,etc using jquery and without write onclick event or etc on the div where I want to get that value.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="test" title="test1">test</div>
<div id="test2" title="test2">test2</div>
<script>
function getVal(attr,value){
$("#show").text("this "+attr+" have value ="+value);
}
$(document).ready(function(){
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
});
</script>
<div id="show"></div>
</body>
</html>
Usually to get some value from div that i click, I add an onclick event on div like
<div id='test' onclick="getVal(test)" ></div>
and it will return "test". And the code that I write above nearly what I want, but the problem that I have is if I have a many div, how can I get the value from each div that I click just using jquery click function and I don't need to write
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
$("#test2").click(function(){
getVal("#test2",$("#test2").attr("title"));
});//and so on
here the code that I use to achieve what I want, using onclick event that I put on div:
<script type="text/javascript">
function overlay(rel){
var value = rel;
$(document).ready(function(){
$(".img"+value).click(function(){
$(".overlay-bg"+value).fadeIn();
});
$(".close"+value).click(function(){
$(".overlay-bg"+value).fadeOut();
})
});
}
</script>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-a.jpg" class="img1" onclick="overlay(1)" title="photo1" alt="photo1"/>
</div>
<div id="overlay-bg" class="overlay-bg1">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/a.jpg"/>
<span>photo1</span>
<span style="font-size:0.8em;"><p>photo a</p></span>
<div id="close" class="close1"></div>
</div>
</div>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-b.jpg" class="img2" onclick="overlay(2)" title="photo2" alt="photo2"/>
</div>
<div id="overlay-bg" class="overlay-bg2">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/b.jpg"/>
<span>photo2</span>
<span style="font-size:0.8em;"><p>photo b</p></span>
<div id="close" class="close2"></div>
</div>
</div>
I'm really want to know how to resolve my problem.
Give the elements you want to attach the click event handler to the same class. Then use the class selector [docs] to select all of them:
$('.sharedClass').click(function() {
getVal(this.id, $(this).attr("title"));
});
jQuery will bind the event handler to each of the selected elements.
There are many ways to select elements [docs], selection by ID or class are just two of them. You might also find the jQuery tutorial useful to get a better idea of how jQuery works.
you can use the this keyword within the handler function, and it will point to the element that was clicked
Here's the correct way to do it.
Put a class name to your target div e.g.
<div id="test" class="clickable" title="test">test</div>
<div id="test2" class="clickable" title="test">test</div>
...
...
Then create a jQuery event with selected class
$('.clickable').click(function(){ ... });
<div id="test">harsh</div>
<script>
alert(document.getElementById('test').innerHTML);
</script>
If you want to call this function with the click of every div, use :
$("div").click(function(){
getVal($(this),$(this).attr("title"));
});
If you want to call the function for a set of divs, but not all, give those divs a class name as suggested by #Felix Kling.
Check out the jQuery Selectors to get a better idea.
Not sure what you're trying to achieve.
If you have multiple values how do you want to store them?
If you have an array that you wanted to populate you can use the each() function on a JQuery selector to traverse all elements selected.
Like so:
var values = new Array();
$(document).ready(function(){
$('#test1, #test2').each(function(){
values.push($(this).html());
});
});
You could also store the values in an associative way to make retrieval a bit easier if you didn't want to iterate through an array. For example you could use the value of the 'title' attribute as the key in the array.
Replace the values.push() line with this line of code:
values[$(this).attr('title')] = $(this).html();

Show elements of a specific class Javascript(Jquery)

<div id=klik>KLIK </div>
<div class="list">
<div class="list-wrapper">
<div class="line">1</div>
<div class="line">2</div>
</div>
<div class="line">3</div>
<div class="line">4</div>
</div>
This is the Html. I use Javscript to hide the whole list first. Then I would like to make a onclick function to show just the first two elements, the two in div list wrapper. This the code i have written.
$(document).ready(function(){
$(".list").hide();
$("#klik").click(function(){
$(".list-wrapper").show();
});
});
The problem it never shows the elements.
You are trying to show an element that is still wrapped inside a hidden parent element. In case you hide and show the same selection it is working just fine. You could do it like this:
$(document).ready(function(){
$(".list").hide();
$("#klik").click(function(){
$(".list").show().children().not('.list-wrapper').hide(); //show .list, then hide everything that is not inside .list-wrapper
});
});​
Working demo
EDIT:
And fix your HTML markup (missing quotes "" ) <div id=klik>KLIK</div>
You are hiding the parent element of what you are trying to show. show will only display the elements you called it on, it won't cascade up the DOM tree.
$(document).ready(function(){
$(".list").hide();
$("#klik").click(function(){
$(".list").show(); //Show .list elements instead
});
});

Categories

Resources