I want all the elements with id #text-field to be hidden (if the browser support JS, that's why it should be hidden with JS). But don't get it to work with elements created this way:
// Add post
$(document).on('click', 'a.add-post', function(event)
{
// Create content based on a hidden item
var newcontent = $('.type-post#post_id-hid-0').html();
content = '<li class="type-post">' + newcontent + '</li>';
// Place new content
$('.posts-list > li.iteration-0').last().after(content);
// Load necessary JS
load_page();
event.preventDefault();
});
And my load_page() function:
$(function()
{
function load_page()
{
$('#text-field').hide();
}
load_page();
}
Use a class for text-field instead of an ID, ID's are unique for each element while a class can be used over again for this purpose.
A lightweight solution which doesn't require any JS to execute, and won't cause a 'jumpy' interface when it first loads and elements disappear in front of users eyes.
CSS:
#text-field{display:hidden;}
HTML:
<noscript>#text-field{display:block;}</noscript>
you have to do two things:
function load_page(){ //<----put this in global scope
$('.text-field').hide(); //<---hide it with class name
}
$(function(){
load_page();
});
so now somewhere in your page you might have this <input type='text' id='text-field' /> here you can change your elem's id to class this way:
<input type='text' class='text-field' />
this should help if you can replace classname with whichever dynamic page related class you insert :
$(".classname[id='text-field']").hide();
or
$(".classname[id='text-field']").attr("style", "display:none");
Related
So I more than one dynamicly generated elements with the same class name that I am trying to check input for in jQuery. Instead of it letting me click on both, it is just letting me click the first element generated.
Ex: I click on item_1 and it returns the item_1 id, but when I click on item_2 it doesn't return anyting.
HTML
<div id="item_1" class="resp"></div>
<div id="item_2" class="resp"></div>
JS - Jquery
$(".resp").on("click",() =>{
var id = $(".resp").attr("id");
console.log('attempting toggle' + id);
});
Firstly, you have to use normal function instead of arrow function (to avoid missing the context). Secondly - use this keyword to refer to the actually clicked element.
$(".resp").on("click", function() {
console.log('attempting toggle ' + this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item_1" class="resp">A</div>
<div id="item_2" class="resp">B</div>
This is because .attr('id') returns the value of the id attribute of the first matched element in the set.
Instead, use an old school function for the handler so the this value is equal to the clicked div, then get its id:
$(".resp").on("click", function() {
var id = $(this).attr('id');
console.log('attempting toggle ' + id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item_1" class="resp">First</div>
<div id="item_2" class="resp">Second</div>
What you're doing here is referencing the classname to obtain the id. This gathers the id of the first classname, which isn't what you desire. What you need to do is use the this keyword to correctly obtain the id.
After removing the arrow function and changing the internal code a bit, it should look like this:
$(".resp").on("click", function() {
var id = this.id;
console.log('attempting toggle: ' + id);
});
Also make sure you've correctly installed JQuery. Pick up your JQuery embed code from here.
Also remember to include your JQuery code before your JavaScript code.
I am trying to customize my basicDay view in fullcalendar like if I click on the event it will slide down a div tag with some content.
Here is my code.
eventRender: function(event, element, view,calEvent) {
if(view.name === 'basicDay') {
proj=event.title;
element.empty();
element.append('<div id="flip" class="flip1" onclick="slide()">'+proj+'</div>');
element.append('<div class="down" id="panel">\n\
Project Name: <input type="text" value="'+proj+'"/>\n\
Date: <input type="date" value="'+dt+'"/>');
element.append('</div>');
$(".fc-today").css("background", "white");
}
},
Here I am clearing task elements and add a custom div tag with the project name. If I have more than one event the Div tag will add dynamically.
The thing is, I need to slide down div with the class="flip1" and show the div with the class="down".
This is how I tried to do it.
function slide()
{
$('.down').slideToggle("fast");
}
The problem is if I have more than one event all the div tag is sliding down. But want to slide down the tag which I will click.Sorry for my bad English, please help me resolve this guys. Thanks in advance.
You are trying to open #panel on clicking the the #flip
You can pass the context using this and then select the next immediate #panel
In dynamically created element
onclick="slide(this)"
Change in js
function slide(elem){
var getNextPanel = $(elem).next("#panel");
getNextPanel.slideToggle("fast");
}
Not tested but you can try this. Also note id like panel & flip cannot be same for all the dynamically created element, id need to be unique
Add a dynamic id to your element and then use a function like below
//id is your dynamic id and call this function on that element like `slide(this.id);`
function slide(id)
{
$('#'+id).slideToggle("fast");
}
I finally managed to do this by the below code.
var x=0;
eventRender: function(event, element, view,calEvent) {
if(view.name === 'basicDay') {
x++;
element.removeClass("fc-event");
element.addClass("day-event");
element.children().addClass("day-event");
proj=event.title;
dt=new Date();
dt=event.date;
element.empty();
element.append('<div id="'+x+'" class="flip1" onclick="slide(this.id)">'+proj+'</div>');
element.append('<div class="'+x+'" id="panel">\n\
Project Name: <input type="text" value="'+proj+'"/>\n\
Date: <input type="date" value="'+dt+'"/>');
element.append('</div>');
$(".fc-today").css("background", "white");
}
},
and I wrote the function like this.
function slide(id)
{
$('.'+id).slideToggle("fast");
}
And this function also working fine.
function slide(id)
{
// $('.'+id).slideToggle("fast");
var getNextPanel = $('#'+id).next("#panel");
getNextPanel.slideToggle("fast");
}
If I need to improve my code further please suggest me guy's.Thank you for all your support guys.
You were right. So here is your working example:
function slide(id)
{
$('#'+id).slideToggle("fast");
}
jQuery:
$('.clickhere').click(function(e){
e.preventDefault();
$(this).closest('.row').children('.abc').hide(); // working
$(this).closest('.row').children('.abc').children('input').value = ''; // not working
$(this).closest('.bookingrow').children('.addressbox').children('input').value(''); // alternative - not working
});
html
<div class="row">
<div class='abc'>
<input type='text' class='unknown' />
</div>
<div class="clickhere">hide</div>
</div>
my target is if i click the "clickhere" class, content under "abc" class will hide and whatever content added by customer on those input box, they will be clear.
same html used multiple time on the same form. that's why using "$(this)".
any solution? what i am doing wrong?
Thanks in advance.
You need to use .val() to set the value, jQuery methods normally will return a jQuery object not a dom element reference so you would not have a properly called .value.
$(this).closest('.row').find('.abc input').val('');
So
$('.clickhere').click(function (e) {
e.preventDefault();
//cache the value of .row since it is used multiple times
var $row = $(this).closest('.row');
$row.children('.abc').hide(); // working
$row.find('.abc input').val('');
});
I'm generating a div dynamically and I've to check whether a dynamically generated div exists or not ? How can I do that?
Currently I'm using the following which does not detects the div generated dynamically. It only detects if there is already an element with the id contained in the HTML template.
$(function() {
var $mydiv = $("#liveGraph_id");
if ($mydiv.length){
alert("HHH");
}
});
How can I detect the dynamically generated div?
If mutation observes aren't an option due to their browser compatibility, you'll have to involve the code that's actually inserting the <div> into the document.
One options is to use a custom event as a pub/sub.
$(document).on('document_change', function () {
if (document.getElementById('liveGraph_id')) {
// do what you need here
}
});
// without a snippet to go on, assuming `.load()` for an example
$('#container').load('/path/to/content', function () {
$(this).trigger('document_change');
});
If it is added dinamically, you have to test again. Let's say, a click event
$("#element").click(function()
{
if($("#liveGraph_id").length)
alert("HHH");
});
How you inserting your dynamic generated div?
It works if you do it in following way:
var div = document.createElement('div');
div.id = 'liveGraph_id';
div.innerHTML = "i'm dynamic";
document.getElementsByTagName('body')[0].appendChild(div);
if ($(div).length > 0) {
alert('exists'); //will give alert
}
if ($('#liveGraph_id').length > 0) {
alert('exists'); //will give alert
}
if ($('#liveGraph_id_extra').length > 0) {
alert('exists'); //wont give alert because it doesn't exist.
}
jsfiddle.
Just for interest, you can also use a live collection for this (they are provided as part of the DOM). You can setup a collection of all divs in the page (this can be done in the head even before the body is loaded):
var allDivs = document.getElementsByTagName('div');
Any div with an id is available as a named property of the collection, so you can do:
if (allDivs.someId) {
// div with someId exists
}
If the ID isn't a valid identifier, or it's held in a variable, use square bracket notation. Some play code:
<button onclick="
alert(!!allDivs.newDiv);
">Check for div</button>
<button onclick="
var div = document.createElement('div');
div.id = 'newDiv';
document.body.appendChild(div);
">Add div</button>
Click the Check for div button and you'll get false. Add the div by clicking the Add div button and check again—you'll get true.
is very simple as that
if(document.getElementById("idname")){
//div exists
}
or
if(!document.getElementById("idname")){
// don't exists
}
I just created script that shows/hides (toggles) block of HTML. There are four buttons that each can toggle its HTML block. When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button... it hides that HTML block and shows new one.
Here is what I have at the moment:
$('.btn_add_event').click( function() {
$('.block_link, .block_photos, .block_videos').hide();
$('.block_event').toggle();
});
$('.btn_add_link').click( function() {
$('.block_event, .block_photos, .block_videos').hide();
$('.block_link').toggle();
});
$('.btn_add_photos').click( function() {
$('.block_event, .block_link, .block_videos').hide();
$('.block_photos').toggle();
});
$('.btn_add_videos').click( function() {
$('.block_event, .block_link, .block_photos').hide();
$('.block_videos').toggle();
});
Any ideas how to reduce code size? Also, this script isn't very flexible. Imagine to add two new buttons and blocks.
like Sam said, I would use a class that all the blocks share, so you never have to alter that code. Secondly, you can try 'traversing' to the closest block, therefore avoiding it's name. That approach is better than hard coding each specific block, but if the html dom tree changes you will need to refactor. Last, but best, you can pass in the class name desired block as a variable to the function. Below is something you can copy paste that is close to what you started with.
$('.myAddButtonClass').click( function() {
$('.mySharedBlockClass').filter(':visible').hide();
//find a good way to 'traverse' to your desired block, or name it specifically for now.
//$(this).closest(".mySharedBlockClass").show() complete guess
$('.specificBlockClass').show();
});
I kept reading this "When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button" thinking that my eyes were failing me when Its just bad English.
If you want to make it more dynamic, what you can do is add a common class keyword. Then
when the click event is raise. You can have it loop though all the classes that have the
keyword and have it hide them all (except the current one that was clicked) and then show the current one by using the 'this' keyword.
you can refer below link,
http://chandreshmaheshwari.wordpress.com/2011/05/24/show-hide-div-content-using-jquery/
call function showSlidingDiv() onclick event and pass your button class dynamically.
This may be useful.
Thanks.
try this
$('input[type=button]').click( function() {
$('div[class^=block]').hide(); // I resumed html block is div
$(this).toggle();
});
Unfortunatly I couldn't test it, but if I can remember right following should work:
function toogleFunc(clickObject, toogleTarget, hideTarget)
{
$(clickObject).click(function()
{
$(hideTarget).hide();
$(toogleTarget).toggle();
});
}
And the call:
toogleFunc(
".btn_add_videos",
".block_videos",
".block_event, .block_link, .block_photos"
);
and so far
Assuming the buttons will only have one class each, something like this ought to work.
var classNames = [ 'btn_add_event', 'block_link', 'block_photos', 'block_videos' ];
var all = '.' + classNames.join(', .'); // generate a jquery format string for selection
$(all).click( function() {
var j = classNames.length;
while(j--){
if( this.className === classNames[j] ){
var others = classNames.splice(j, 1); // should leave all classes but the one on this button
$('.' + others.join(', .')).hide();
$('.' + classNames[j]).toggle();
}
}
}
All the buttons have the same handler. When the handler fires, it checks the sender for one of the classes in the list. If a class is found, it generates a jquery selection string from the remaining classes and hides them, and toggles the one found. You may have to do some checking to make sure the strings are generating correctly.
It depends by how your HTML is structured.
Supposing you've something like this
<div class="area">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
...
<div class="sender">
<a class="one"></a>
<a class="two"></a>
<a class="three"></a>
</div>
You have a class shared by the sender and the target.
Your js would be like this:
$('.sender > a').click(function() {
var target = $(this).attr('class');
$('.area > .' + target).show().siblings().hide();
});
You show your real target and hide its siblings, which aren't needed.
If you put the class postfixes in an array, you can easily make this code more dynamic. This code assumed that it doesn't matter in which order toggle or hide are called. If it does matter, you can just remember the right classname inside the (inner) loop, and toggle that class after the loop.
The advantage to this approach is that you can extend the array with an exta class without needing to modifying the rest of the code.
var classes = new Array('videos', 'event', 'link', 'photos');
for (var i = 0; i < classes.length; ++i)
{
$('.btn_add_' + classes[i]).click(
function()
{
for (var j = 0; j < classes.length; ++j)
{
if (this.hasClass('btn_add_' + classes[j]))
{
$('.block_' + classes[j]).toggle();
}
else
{
$('.block_' + classes[j]).hide();
}
}
});
}
You could make this code more elegant by not assigning those elements classes like btn_add_event, but give them two classes: btn_add and event, or even resort to giving them id's. My solution is based on your description of your current html.
Here is what I think is a nice flexible and performant function. It assumes you can contain your links and html blocks in a parent, but otherwise it uses closures to precalculate the elements involved, so a click is super-fast.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script>
<script type="text/javascript">
// Enables show/hide functionality on click.
// The elements within 'container' matching the selector 'blocks' are hidden
// When elements within 'container' matching the selector 'clicker' are clicked
// their attribute with the name 'clickerAttr' is appended to the selector
// 'subject' to identify a target, usually one of the 'blocks'. All blocks
// except the target are hidden. The target is shown.
//
// Change clickerAttr from 'linkTarget' to 'id' if you want XHTML compliance
//
// container: grouping of related elements for which to enable this functionality
// clicker: selector to element type that when clicked triggers the show/hide functionality
// clickerAttr: name of the DOM attribute that will be used to adapt the 'subject' selector
// blocks: selector to the html blocks that will be shown or hidden when the clicker is clicked
// subject: root of the selector to be used to identify the one html block to be shown
//
function initToggle(container,clicker,clickerAttr,blocks,subject) {
$(container).each(
function(idx,instance) {
var containerElement = $(instance);
var containedBlocks = containerElement.find(blocks);
containerElement.find(clicker).each(function(idxC, instanceClicker) {
var tgtE = containerElement.find(subject+instanceClicker.getAttribute(clickerAttr));
var clickerBlocks = containedBlocks.not(tgtE);
$(instanceClicker).click(function(event) {
clickerBlocks.hide();
tgtE.toggle();
});
});
// initially cleared
containedBlocks.hide();
}
);
}
$(function() {
initToggle('.toggle','a.link','linkTarget','div.block','div.');
});
</script>
</head>
<body>
Example HTML block toggle:
<div class="toggle">
a <br />
b <br />
c <br />
<div class="A block"> A </div>
<div class="B block"> B </div>
<div class="C block"> C </div>
</div> <!-- toggle -->
This next one is not enabled, to show scoping.
<div class="toggle2">
a <br />
<div class="A block">A</div>
</div> <!-- toggle2 -->
This next one is enabled, to show use in multiple positions on a page, such as in a portlet library.
<div class="toggle">
a <br />
<div class="A block">A</div>
</div> <!-- toggle (2) -->
</body>
</html>