I am using materialize to create an accordion collapsible on my page. I want to add gifs/images to my page when the collapsible header is clicked and want to remove them when that collapsible header is clicked again or another header is clicked.
I am able to add the gifs on click but have not been able to figure out how to remove them. I am using javascript and jquery.
Below is my code:
contentTitles = ["Test1", "Test2", "Test3"];
contentLinks = ["test1.gif", "test2.gif", "test3.gif"];
$(document).ready(function(){
$('.collapsible').collapsible();
$('main').append('<ul data-collapsible="accordion"></ul>');
$('ul').addClass('collapsible popout');
for (var j = 0; j < contentTitles.length; j++) {
$('ul').append('<li></li>');
// start the creation of the collapsible
$('.collapsible').collapsible({
accordion: false, // A setting that changes the collapsible behavior to expandable instead of the default accordion style
});
};
// create the collapsible
$('li').append('<div><i></i></div>');
$('li').append('<div><span></span></div>');
$('i').addClass('material-icons');
$('i').parent().addClass("collapsible-header hoverable");
$('span').parent().addClass("collapsible-body");
// adds the titles to each collapsible header
$('.collapsible-header').each(function(index) {
$(this).html(contentTitles[index]);
})
// adds the gif urls to each collapsible body
$('.collapsible-header').on('click', function() {
$('.collapsible-body').each(function(index) {
$(this).html('<iframe class="gif" src=' + contentLinks[index] + '>');
})
})
$('.collapsible-header').on('click', function() {
$('.collapsible-body').html();
})
})
});
Thank you.
The .html() call just returns the html content of the element - it doesn't change it. If you want to empty the element, do this:
$('.collapsible-header').on('click', function() {
$('.collapsible-body').html(""); //set HTML to be an empty string
})
Related
I am creating an plugin with wordpress for the portfolio items. Everything works fine . But the issue is when i apply the filter the hover effect stopped working on the cloned items
also available JS FIDDLE
the jquery code is given below i tried
/* Scroll to Top Button */
jQuery(document).ready(function() {
// Animate Box Shadow on some elements
// Add the overlay. We don't need it in HTML so we create it here
// Clone portfolio items to get a second collection for Quicksand plugin
var $portfolioClone = jQuery(".rudra-portfolio").clone(true);
// Attempt to call Quicksand on every click event handler
jQuery(".rudra-portfolio-filter a").click(function(e) {
jQuery(".rudra-portfolio-filter li").removeClass("current");
// Get the class attribute value of the clicked link
var $filterClass = jQuery(this).parent().attr("class");
if ($filterClass == "all") {
var $filteredPortfolio = $portfolioClone.find("li");
} else {
var $filteredPortfolio = $portfolioClone.find("li[data-type~=" + $filterClass + "]");
}
// Call quicksand
jQuery("ul.rudra-portfolio").quicksand($filteredPortfolio, {
duration: 500,
easing: 'easeInOutQuad'
});
jQuery(this).parent().addClass("current");
// Prevent the browser jump to the link anchor
e.preventDefault();
})
jQuery(".port-li").click(function() {
jQuery(this).find('.content-wrapper').slideDown();
});
jQuery(".overeffect").mouseover(function() {
jQuery(this).find('.content-wrapper').slideDown();
});
jQuery("#portfolio-grid li").mouseleave(function() {
jQuery('.content-wrapper').slideUp(500);
});
});
hour effect is working fine for first and second time , but after that it stopped working .
Update
I also tried this Jquery clone
solved by me ..
i just need to use this
jQuery(document).on('hover',".overeffect",function(){
jQuery(this).find('.content-wrapper').slideDown();
});
I am working on a class project and need to be able to toggle the background color of a transparent png on click. I have been working through a number of examples from the site, but I can't get it working. I am a total novice at Javascript and haven't had luck trying to plug in jQuery code either.
Here is the targeted section:
<div class="expenseIcon"><a href="#">
<img src="images/mortgage.png"></a><br/>
<p>Rent or Mortgage</p>
</div>
On clicking the linked image, the goal is for the background on the image to change to green. Clicking it again would change it back to the default, white. Here's the CSS I'd like to toggle on/off with click.
.colorToggle {
background: #A6D785;
}
I had tried adding class="iconLink" to the href and class="iconBox" to the image with the following Javascript adapted from another post, but it didn't work.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
//alert(obj.var1);
//return false;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
Any advice would be greatly appreciated!
Let's break down what is happening with your current code when you click the link.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
JQuery finds all elements with the classname "iconBox". In your case, this is the img element. The reference to that element is then saved in "obj.var1". You do not end up doing anything with this reference, so these two lines can be removed.
All elements with the class "iconBox" have the class "colorToggle" removed. Your img element didn't have this class on it, so nothing happens.
The class "colorToggle" is added to the anchor element. Yes! Now the element wrapping the img has a background color.
Unfortunately, clicking the anchor tag again won't do anything, since the anchor tag will already have the "colorToggle" class and all we would be doing would be trying to add it again. Hmm. Let's try changing addClass to toggleClass. Here's our new code:
$(document).ready(function () {
$(".iconLink").click(function () {
$(this).toggleClass('colorToggle');
}
});
Also, note that because we're working with the anchor element, the p element won't be affected by this change. If you want the entire div to change background colors, use this line instead:
$(".expenseIcon").toggleClass('colorToggle');
Using the given markup:
<!-- to toggle the bg-color onClick of anchor tag -->
<div class="expenseIcon">
<a href="#">
<img src="images/mortgage.png">
</a>
<br/>
<p>Rent or Mortgage</p>
</div>
since the question asks for javascript, heres an option for updating the background-color of an element using the built-in js.style method
//get a handle on the link
//only one element w/ className 'expenseIcon'
//first child of 'expenseIcon' is the anchor tag
var link = document.getElementsByClassName('expenseIcon')[0].children[0];
//get a handle on the image
var image = link.children[0];
//listen for click on link & call bgUpdate()
link.addEventListener('click', bgUpdate, false);
function bgUpdate() {
if(image.style.backgroundColor === 'lightgoldenrodyellow'){
image.style.backgroundColor = 'aliceblue';
} else if (image.style.backgroundColor === 'aliceblue') {
image.style.backgroundColor = 'lightgoldenrodyellow';
}
else console.log('image bgColor: ' + image.style.backgroundColor);
}
a similar example
css
.expenseIcon{
background: red;
}
.colorToggle {
background: blue;
}
jquery
$(".expenseIcon").click(function () {
$('.expenseIcon').toggleClass('colorToggle');
});
By default, the div will have expenseIcon background. ToggleClass will toggle the div class with colorToggle so will override the previous color.
You don't need an hyperlink tag A to manage clicks, just put it on the DIV.
I'm trying to create previous / next buttons on each accordion body.
I can't figure out a way to collapse / expand a certain section. I tried removing the class in from the accordion-body but that does not seem to collapse.
$(".accordion-body").each(function(){
if($(this).hasClass("in")) {
$(this).removeClass("in");
}
});
Also whenever or whatever I use the .collapse method on, I get a javascript error saying that object has no method collapse.
The in class is just an indicator that a section is open. The Javascript module applies the same inline styles as .in does, so removing the class is insufficient.
You need to use the module's API to programmatically interact with the accordion, via the .collapse() method:
$('.accordion-body').each(function(){
if ($(this).hasClass('in')) {
$(this).collapse('toggle');
}
});
Or, you can condense this down to:
$('.accordion-body.in').collapse('toggle');
If you want only to collapse any open sections:
$('.accordion-body').collapse('hide');
If you want only to expanded any closed sections:
$('.accordion-body').collapse('show');
Here is another solution:
/**
* Make an accordion active
* #param {String} id ID of the accordion
*/
var activateAccordion = function (id) {
// Get the parents
var parents = $('a[href="#' + id + '"]').parents('.panel-group').children('.panel');
// Go through each of the parents
$.each(parents, function (idx, obj) {
// Check if the child exists
var find = $(obj).find('a[href="#' + id + '"]'),
children = $(obj).children('.panel-collapse');
if (find.length > 0) {
// Show the selected child
children.removeClass('collapse');
children.addClass('in');
} else {
// Hide the others
children.removeClass('in');
children.addClass('collapse');
}
});
};
The important part of the code is the combination, remembering the .collapse class, not just using .in:
// Show the selected child
children.removeClass('collapse');
children.addClass('in');
and
// Hide the others
children.removeClass('in');
children.addClass('collapse');
The above example has been tested in Twitter's Bootstrap v3.3.4
This works for accordions in Bootstrap 3:
var selector = $('.panel-heading a[data-toggle="collapse"]');
selector.on('click',function() {
var self = this;
if ($(this).hasClass('collapsed')) {
$.each(selector, function(key, value) {
if (!$(value).hasClass('collapsed') && value != self) {
$(value).trigger('click');
}
});
}
});
I'm simulating a click of the other accordion tabs with $(value).trigger('click');. According to the API you should just be able to use the .collapse() method i.e. $(value).collapse('hide');. But it doesn't work for some reason so trigger it is...
For this kind of problem use addClass("in"); only because of using ".collapse('toggle/Hide/Show');" will disturb the future toggle functionality.
Another related use case is when we have forms inside accordions & we want to expand accordion with validation errors. Extending the answer by Daniel Wright
https://stackoverflow.com/a/12698720/6504104, we can do something like
/**
* Expands accordions that have fields with errors
*
*/
var _expandAccordions = function () {
$form = $('.my-input-form');
// you can adjust the following lines to match your form structure / error classes
var $formGroups = $form.find('.form-group.has-error');
var $accordions = $formGroups.closest('.accordion-body');
$accordions.each(function () {
$(this).collapse('show');
});
};
I did,
$('.mb-0').click(function(){
$('.collapse').collapse('hide');
$('.collapse.in').collapse('show');
});
and this works for me
Using Bootstrap 4 add the following buttons inside the card body
<input type="button" class="btn btn-secondary btn-block btn-sm mt-3 text-center card-proceed-next" value="Proceed" />
<input type="button" class="btn btn-secondary btn-block btn-sm mt-3 text-center card-proceed-prev" value="Previous" />
Add the following javascript (includes Azhar Khattak show panels with validation errors):
$(function () {
$('.card-proceed-next').click(function (e) {
e.preventDefault();
$(e.target).closest('.collapse').collapse('hide'); // hide current accordion panel
$(e.target).closest('.card').next('.card').find('.collapse').addClass('show'); // show next accordion panel
});
$('.card-proceed-prev').click(function (e) {
e.preventDefault();
$(e.target).closest('.collapse').collapse('hide'); // hide current accordion panel
$(e.target).closest('.card').prev('.card').find('.collapse').addClass('show'); // show previous accordion panel
});
var $elErrors = $('#accordion').find('.field-validation-error'); // elements with error class
var $accordionsWithErrors = $elErrors.closest('.collapse'); // accordions with error elements
if ($accordionsWithErrors.length > 0) $('.collapse').collapse(); // collapse all accordion panels due to the first accordion panel shown as default
$accordionsWithErrors.each(function () {
$(this).addClass('show'); // show accordion panels with error messages
});
});
i have a little javascript function that does something when one clicks on the element having onclick that function.
my problem is:
i want that, into this function, to set a font color fot the html element having this function onclick. but i don't suceed. my code:
<script type="text/javascript">
function selecteazaElement(id,stock){
document.addtobasket.idOfSelectedItem.value=id;
var number23=document.addtobasket.number;
number23.options.length=0;
if (stock>=6) stock=6;
for (i=1;i<=stock;i++){
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
}
</script>
and how i use it:
<li id = "product_types">
<a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?></a>
</li>
any suggestions? thanks!
i have added another function (jquery one) that does partially what i need. the new problem is: i want that background color to be set only on the last clicked item, not on all items that i click. code above:
$(document).ready(function() {
$('.product_types > li').click(function() {
$(this)
.css('background-color','#EE178C')
.siblings()
.css('background-color','#ffffff');
});
});
any ideas why?
thanks!
I would suggest
$(document).ready(function() {
$('.product_types > li').click(function() {
$('.product_types > li').css('background-color','#FFFFFF');
$(this).css('background-color','#EE178C');
});
});
Your element could have this code:
<li id = "product_types" onclick="selecteazaElement(this);" <...> </li>
To change the foreground color of that element:
function selecteazaElement(element)
{
element.style.foregroundColor="#SOMECOLOR";
}
If you want to change the background color on only the last element clicked, each element must have a different id. I'd suggest naming each one something like product_types1, product_types2, ..., product_typesN, and so on. Then have a reset function:
function Reset()
{
for (var i = 1; i <= N; i = i + 1)
{
document.getElementById('product_types'+i).style.backgroundColor="#RESETCOLOR";
}
}
When you call your selecteazaElement(this) function, first call the Reset function, then set the new element:
function selecteazaElement(element)
{
Reset();
element.style.backgroundColor="#SOMECOLOR";
}
This way all of the elements that start with product_types followed by a number will be reset to one particular color, and only the element clicked on will have the background changed.
The 'scope' of the function when invoked is the element clicked, so you should be able to just do:
function selecteazaElement(id,stock){
document.addtobasket.idOfSelectedItem.value=id;
var number23 = document.addtobasket.number;
number23.options.length=0;
if (stock>=6){
stock=6;
}
for (var i=1;i<=stock;i++){
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
// Alter 'this', which is the clicked element in this case
this.style.backgroundColor = '#000';
}
$(function() {
/*if product_types is a class of element ul the code below
will work otherwise use $('li.product_types') if it's a
class of li elements */
$('.product_types li').click(function() {
//remove this class that causes background change from any other sibling
$('.altBackground').removeClass('altBackground');
//add this class to the clicked element to change background, color etc...
$(this).addClass('altBackground');
});
});
Have your css something like this:
<style type='text/css'>
.altBackground {
background-color:#EE178C;
/* color: your color ;
foo: bar */
}
</style>
Attach a jQuery click event to '#product_types a' that removes a class from the parent of all elements that match that selector; then, add the class that contains the styles you want back to the parent of the element that was just clicked. It's a little heavy handed and can be made more efficient but it works.
I've made an example in jsFiddle: http://jsfiddle.net/jszpila/f6FDF/
try this instead:
//ON PAGE LOAD
$(document).ready(function() {
//SELECT ALL OF THE LIST ITEMS
$('.product_types > li').each(function () {
//FOR EACH OF THE LIST ITEMS BIND A CLICK EVENT
$(this).click(function() {
//GRAB THE CURRENT LIST ITEM, CHANGE IT BG, RESET THE REST
$(this)
.css('background-color','#EE178C')
.siblings()
.css('background-color','transparent');
});
});
});
If I am correct, the problem is that the click event is being binded to all of the list items (li). when one list item is clicked the event is fired on all of the list items.
I added a simple .each() to your code. It will loop through each of the list items and bind a event to each separately.
Cheers,
-Robert Hurst
I am changing an accordion structure () and changing it based on a choice using AJAX.
The problem is, based on the accordion docs, I expect it to work like
<h3>header</h3>
<div><anything></anything></div>
Making the h3 stuff the header and the div stuff the body, but when I use ajax to dynamically create it it screws up. This code specifically uses the correct header for the first accordion box, but the body is empty and the next header becomes "There are no open session windows..." which is clearly not what I wanted. The JSON this gets is here: http://benbuzbee.com/trs/json.php?show=sessions&courseid=5
$(function() {
$("#courseselect").change(function () {
$("#testselect").accordion("destroy").html(""); // Empty any previous data
$("#testselect").css("display", "block"); // Display it if it was hidden
$.getJSON('json.php?show=sessions&courseid=' + $(this).val(), function(data) {
for (x in data)
{
$("#testselect").append("<h3>" + data[x].name + "</h3>");
$("#testselect").append("<div>");
if (!data[x].sessions)
$("#testselect").append("<p>There are no open session windows for this test.</p>");
for (si in data[x].sessions)
{
$("#testselect").append(""+data[x].sessions[si].location+"");
}
$("#testselect").append("</div>");
}
$("#testselect").accordion();
//$("#testselect").accordion({ change:function(event, ui) { courseid = ui.newHeader.attr("value"); }
}); // End getJSON
}); // end .change
}); // end $()
I think I see a few problems.
Your statement
$("#testselect").append("<div>")
will append BOTH an opening and a closing tag to #testSelect like this:
<div id='testselect'><h3><a> </a> </h3><div></div> </div>
Any further appending to #testselect will append elements AFTER the div tags.
Your next statement,
$("#testselect").append("<p>There are no open session windows for this test.</p>");
Will do this
<div id='testselect'><h3><a></a></h3><div></div><p> There are no open session windows for this test. </p> </div>
Your statement
$("#select.").append("</div>")
will NOT append a closing div tag to #testselect like you seem to be intending. Instead, it will do nothing.
You should change your for loop to something like this:
for (x in data)
{
var $header = $("<h3>").appendTo("#testSelect");
$header.append("" + data[x].name + "")
var messageContainer = $("<div>").appendTo($header);
if (!data[x].sessions)
messageContainer.append("<p> There are no open session windows for this test </p>");
for (si in data[x].sessions)
{
messageContainer.append(""+data[x].sessions[si].location+"");
}
$("#testselect").accordion();
}