Change div id attribute on click - javascript

I have two divs. When I click on a button it moves to another div
Here is it looks like
I realize it like this
var counter = 0;
$('.click2').on('click', function () {
counter++;
if (counter > 10) {
return false;
}
else {
var elem = $(this).closest('.title');
$('.title2').append($(elem).html()).show();
}
});
But I have one problem I need to change Id of elements when it moves
I know that is realizing like this
$(this).attr('id', '.title_left');
But I can have 1-10 divs in left column and need to name it .title_left1. Next will be title_left2 and ++
How I can code it?

You can just append counter to the id attribute:
$(this).attr('id', '.title_left' + counter);

Related

Adding Next and Previous Buttons to Bootstrap Targeting Link IDs

I am attempting to add next/prev and then swipe events to a bootstrap modal image gallery. The thumbnails are displayed in a grid so when I try closest(), siblings(), and next() I am only able to go to the images below and above in the same column and not the other columns in the grid.
Each thumbnail has an id with the images ID in the database. ie:
<a class="image-gallery-item" id="img-1002" href="#showImageModal" data-toggle="modal" onclick="..."><img src="..." /></a>
<a class="image-gallery-item" id="img-4664" href="#showImageModal" data-toggle="modal" onclick="..."><img src="..." /></a>
Every link passes the images src, caption, and ID to a function which changes out the info displayed the modal. All that works fine, I just can't seem to get next/prev working when trying to trigger the next item.
Ideally, instead of using next() and closest() and sibling() methods, I would LIKE to just target the ID greater than the current id for first next and lesser than the current ID for the first previous and trigger a click if the element exists.
Thanks.
UPDATE
Per #Ersian's suggestion, I created an array and cycle thru the images by index. They're still going by column but at least they're moving to the next column after. This will present a little confusion for users, I feel, who will expect the images to display left to right before going to the next row of square thumbnails.
$('.image-gallery-item').modal('hide');
setTimeout(function () {
var thisIMG = $("#imgid").html();
var imgs = document.getElementsByClassName("image-gallery-item");
var $imgvalues = Array.prototype.map.call(imgs, function (el) {
return el.id;
});
index = $imgvalues.indexOf(thisIMG);
if (index >= 0 && index < $imgvalues.length - 1)
nextItem = $imgvalues[index + 1];
$('#' + nextItem).trigger('click');
}, 1000);
UPDATE - WORKING CODE
Found the solution by adding sort to the array and then looped the next/prev if hitting the end or start of items with the class image-gallery-item. I'll post the working code as an answer in case anyone else finds this question and wants to make a bootstrap modal image gallery with gridalicious, isotope, or masonry layouts with columns.
Keep in mind you will need to add buttons with show-next-image and show-previous-image classes to your modal. After that, the following code will let you cycle thru images with the class image-gallery-item.
$('#show-next-image, #show-previous-image').click(function () {
if ($(this).attr('id') == 'show-previous-image') {
$('#showImageModal').modal('hide');
setTimeout(function () {
var thisIMG = $("#imgid").html();
var imgs = document.getElementsByClassName("image-gallery-item");
var $imgvalues = Array.prototype.map.call(imgs, function (el) {
return el.id;
});
var lastIMG = $('.image-gallery-item').length;
$imgvalues.sort();
index = $imgvalues.indexOf(thisIMG);
if (index <= lastIMG - 2) {
nextItem = $imgvalues[index + 1];
} else {
nextItem = $imgvalues[0];
}
$('#' + nextItem).trigger('click');
}, 1000);
} else {
$('#showImageModal').modal('hide');
setTimeout(function () {
var thisIMG = $("#imgid").html();
var imgs = document.getElementsByClassName("image-gallery-item");
var $imgvalues = Array.prototype.map.call(imgs, function (el) {
return el.id;
});
var lastIMG = $('.image-gallery-item').length;
$imgvalues.sort();
index = $imgvalues.indexOf(thisIMG);
if (index >= 1) {
nextItem = $imgvalues[index - 1];
} else {
nextItem = $imgvalues[lastIMG - 1];
}
$('#' + nextItem).trigger('click');
}, 1000);
}
});

How to show/hide certain number of divs using a single button?

I have elements that should show or hide after the first five elements. When I click on 'Load More...' with an id #loadMore, it will trigger to show all the elements and change the div id to #showLess to execute a different set of action. So, when I click #showLess to hide the rest of the thumbnails, nothing happens. The $('#showLess').click(function() isn't executing but instead executes the $('#loadMore').click(function() again.
Here's a jsfiddle.
jQuery:
var vidThumbnail = "";
var elements = $('.section.thumbnail .thumb > .video-thumbnail');
for (i = 0; i < 25; i++) // loop thru 25 thumbnails
{
vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';
$('.section.thumbnail .thumb').append(vidThumbnail);
if(i > 5) // when it reaches the first five thumbnails, hide the rest
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
}
$('#loadMore').click(function() // show them all
{
$('.section.thumbnail .thumb .video-thumbnail').show();
$(this).attr('id', 'showLess'); // change id to show less
$(this).text('Show Less...'); // change text value
});
$('#showLess').click(function()
{
// slice the first five, hide the rest
$(elements).slice(5).each(function(i)
{
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
});
$(this).attr('id', 'loadMore'); // change id to show less
$(this).text('Load More...'); // change text value
});
I've fixed a bit your code because you do some mistakes.
Look here: https://jsfiddle.net/sbz51wdz/36/
I explain your error:
When you define a click action, jQuery add an event on a matched DOM elements. If you simply change the id attribute and attach another event of that new ID before the action of changing ID was started, jQuery will not find anything with the new ID. My favourite solution is add the click event on single element with a fixed class or id. Inside the function, everytime, check if the element has or not a class, and then do the right action. Just use somenthing like $(this).hasClass(...)
After this, is better to define single function called when it needs.
Last but not least, it's important to attach assignments after the context is defined in the DOM. so var elements = $('.section.thumbnail .thumb > .video-thumbnail'); this have to be written after the foreach cycle that generate the elements.
Hope its help! :)
You are changing the id of the div on click so should use $(document) and bind all ids with that like
$(document).on('click', '#loadMore', function()
https://jsfiddle.net/sbz51wdz/35/
I have created a div class name "test" and put the loadMore div inside it for binding. You need it cause a hidden or invisible div need to bind in every event occurrence in jquery. then i modified the jquery code in this below way and it works.
var vidThumbnail = "";
var elements = $('.section.thumbnail .thumb > .video-thumbnail');
for (i = 0; i < 25; i++) // loop thru 25 thumbnails
{
vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';
$('.section.thumbnail .thumb').append(vidThumbnail);
if(i > 5) // when it reaches the first five thumbnails, hide the rest
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
}
$('.test').on('click', '#loadMore', function() // show them all
{
$('.section.thumbnail .thumb .video-thumbnail').show();
$(this).attr('id', 'showLess'); // change id to show less
$(this).text('Show Less...'); // change text value
});
$('.test').on('click', '#showLess', function()
{
// slice the first five, hide the rest
var j = 6;
$('.section.thumbnail .thumb .video-thumbnail').each(function(i)
{
$('.section.thumbnail .thumb .video-thumbnail').eq(j).hide();
j++;
});
$(this).attr('id', 'loadMore'); // change id to show less
$(this).text('Load More...'); // change text value
});

Looping inside jQuery function only issue

I'm having some trouble with jQuery in Meteor - I'm just trying to learn so I hope someone could help.
So when #addButton is clicked it will append the div to the .formField and each div created on click will have an unique class, eg formField[1], formField[2] etc
The trouble is when the button is clicked instead of just changing the name of the div only, the div is also added 50 times. I know how dumb it sounds as its a loop, but how would I loop only the div's class on click so each have a different name?
My code is below:
Template.form.events({
'click #addButton': function(event) {
var i;
for (i = 0; i < 50; i++) {
$(".formField").append('<div class="formField['+i+']">.....</div>');
}
return false;
If I understand what you are doing here you don't need a loop. You just need a variable to increment every time the button is clicked. Take your append out of the loop and instead on click increment your variable by one then call an append. No loop necessary.
var i = 0;
Template.form.events({
'click #addButton': function(event) {
i += 1;
$(".formField").append('<div class="formField['+i+']">.....</div>');
}
});
return false;
Do it like this, (i.e. by creating a closure), click run to verify
var uuid = 0;
$('#addButton').on('click', function (event) {
uuid = uuid + 1;
$(".formField").append('<div class="formField[' + uuid + ']">Form' + uuid + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="formField"></div>
<input type="button" value="Add New" id="addButton"></input>

javascript: dynamically remove divs

I'm very new to javascript. The page I am creating has a bunch of forms on it that will hold different data. I've managed to put together the following script that allows me to add more divs by ID.
What I would now like to do is be able to add a button to each of the new divs that allows that specific div to be removed.
var counter = 1;
var limit = 30;
function addInput(what) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var container = document.getElementById(what);
var clone = container.cloneNode(true);
clone.setAttribute('id','div_'+document.getElementById(what).getElementsByTagName('div').length);
container.appendChild (clone);
counter++;
}
}
var remButton=document.createElement('button');
remButton.textContent='Remove';//or something else
remButton.addEventListener('click',function(){
this.parentNode.parentNode.removeChild(this.parentNode)
},false);
clone.appendChild(remButton);
Put that just before container.appendChild(clone);

Removing <p> element with jQuery

This is a jQuery function that determines the class of an image within a table and acts accordingly. If the image parent doesn't have the class selected, it gives it that class and then adds the td id to a div (order). If it does have the class selected, it should remove the class, which it does, and then remove the p element containing the td id.
$(document).ready(function () {
$('td img').click(function () {
if ($(this).parent().hasClass('x')) {
alert("Seat " + ($(this).parent().attr("id")) + " is taken");
} else if ($(this).parent().hasClass('selected')) {
$(this).attr('src', 'images/a.gif');
$(this).parent().removeClass('selected');
var z = $(this).parent().attr('id');
$(z).remove();
return false;
} else {
$(this).attr('src', 'images/c.gif');
$(this).parent().addClass('selected');
alert($(this).parent().attr("class"));
var z = $(this).parent().attr('id');
$('<p>').attr('id', z).text(z).appendTo('#order');
return false;
};
});
});
It works up until removing the p element, where it just doesn't. The p id is dynamically set and is the same as the td id, hence the use of a variable to choose the id.
Ok, so it was a combination of answers on here.
Firstly, the ids weren't unique, so I added a suffix to them:
var z = $(this).parent().attr('id');
$('<p>').attr('id', z+'1' ).text(z).appendTo('#order');'
Then used the suggestion of $('#' + z).remove(); but changed it for my new suffix, so it now shows this $('#' + z+'1').remove();
All seems to be working now, thanks for your help.

Categories