Toggle into for loop - javascript

I want to ask about multiple toggle into a for loop.
for example, when I click into a div, a toggle menu appear.
this is my code:
for (var i = 0; i < myObjectString.length; i++) {
var obj = JSON.parse(myObjectString);
document.getElementById("endorsment").innerHTML += "<div id='endor'>\n\
<div class='endo_"+ obj.Endorsment[i].lang + "' id='endo'>\n\
<div id='count'>"+ obj.Endorsment[i].ln + "</div>\n\
<div id='proglang'>"+ obj.Endorsment[i].lang +"</div>\n\
</div>\n\
<div class='contenthover_"+ obj.Endorsment[i].lang +"' id='contenthover'>\n\
<a class='delete'>\n\
<img src='http://icons.iconarchive.com/icons/icojam/blue-bits/16/symbol-delete-icon.png' />\n\
</a>\n\
<span class='devider'>-</span>\n\
<a class='mybutton'>\n\
<img src='http://icons.iconarchive.com/icons/custom-icon-design/flatastic-1/16/comment-icon.png' />\n\
</a>\n\
<span class='devider'>-</span>\n\
<a class='mybutton'>\n\
<img src='http://icons.iconarchive.com/icons/icojam/blue-bits/16/information-icon.png' />\n\
</a>\n\
</div>\n\
</div>";
$('.endo_'+ obj.Endorsment[i].lang).click(function () {
//$('#contenthover').toggle();
alert(obj.Endorsment[i].lang);
});
This LINK
Any one can help me?

You don't have to use your click code inside the for loop. That make no sense.. It will be inserted no. of times inside your document (DOM).
Use pseudo query selectors. That will definitely make your work easier.
$("[class*='endo']").click(function () {
//do something here.
$(this).next().toggle();
});
next() selector selects the next sibling from the DOM. I have made a wrapper class to improve your css. Take a look at the fiddle for better understanding.
if you remove the wrapper class you may find some problems displaying your "contenthover".
Here's is your updated fiddle.
http://jsfiddle.net/xK0nB1n/2jaLg60o/11/

Related

Add a class to an element with javascript

I was wondering if someone could help me. I'm trying to add .fancy-btn to the below using JavaScript.
<div class="button transparent_2">
<a class="extra-color-3" href="#">Get a quote</a>
</div>
I want .fancy-btn class added to the div container, but cant seem to figure out how to achieve is
Thanks
You need to use .addClass():
$(".transparent_2").addClass('fancy-btn')
see here: https://stackoverflow.com/a/507157/3503886
Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.
<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>
Then
var d = document.getElementById("div1");
d.className = d.className + " otherclass";
Here is a JavaScript only method:
var $a = document.getElementsByClassName("transparent_2");
//assuming there is only 1 element (or is the first)
$a[0].className += " fancy-btn";
JSFiddle

Determining which element was clicked and conditionally choosing which method to call

I am attempting to use JQuery to make 3 thumbnails into buttons that each open up their own page element with details regarding the picture.
Right now I have succeeded in making it so that any thumbnail causes a page element (of the class "description") to scroll open and closed when any thumbnail (from the class "thumbnail") is clicked.
How do I check which thumbnail is clicked on so that I can open a different description corresponding to that specific thumbnail? (This is what I was attempting to do with the "select").
var main = function() {
$('.thumbnail').click(function(select) {
var description = $('.game-descriptions').children('.description');
if( description.is(":hidden")) {
description.slideDown("slow");
}
else
description.hide();
});
}
$(document).ready(main);
Use a data attribute to specify what the thumbnail click is targeting, example: data-target="#game-1", add IDs to your descriptions that match and use data() to use the attribute value of #game-1 a jQuery selector.
Here is a demo
JS
$('.thumbnail').click(function() {
var gameId = $(this).data('target');
$(gameId).slideToggle().siblings(':visible').slideToggle();
});
HTML
<img class="thumbnail" data-target="#game-1" />
<img class="thumbnail" data-target="#game-2" />
<div class="game-descriptions">
<div id="game-1" class="description"></div>
<div id="game-2" class="description"></div>
</div>
Any toggling like toggle(), slideToggle(), fadeToggle() handles the is hidden or is visible
jsFiddle
The parameter to the click function is a jQuery event object, which can be useful in adding some event handling logic. However, within the context of the handler, this refers to the element which triggered the click event, and is typically sufficient for any targeted logic.
Assuming the thumbnails and descriptions have similarly named IDs, for example, you can do something like this:
$(function () {
$('.thumbnail').click(function (event) {
var descId = this.id.replace("thumb", "desc");
var description = $('.game-descriptions').children('#' + descId);
// or simply $("#" + descId);
description.toggle("slow");
});
});
HTML
<div>
<div class="thumbnail" id="thumb-1">Thumb 1</div>
<div class="thumbnail" id="thumb-2">Thumb 2</div>
<div class="thumbnail" id="thumb-3">Thumb 3</div>
</div>
<div class="game-descriptions">
<div class="description" id="desc-1">Description One</div>
<div class="description" id="desc-2">Description Two</div>
<div class="description" id="desc-3">Description Three</div>
</div>
Your technique for targeting the correct 'description' will depend on your actual DOM structure, however.
Also note that I substituted the toggle method for your if statement, as the logic you have is equivalent to what it does (i.e. toggling object visibility).

If href equals id of another div do function

I have a hidden div with the details of a thumbnail that is visible on the page. When you click on the thumbnail, it should fadein or slideup the div with details.
I have set with jquery incremented ID's to each ".portfolio-item-details" to identify each one and then have set with jquery the same ID's to the href of the thumbnail.
<section id="portfolio1" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio1" title="">
<img src="thumbnail.jpg">
</a>
<section id="portfolio2" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio2" title="">
<img src="thumbnail.jpg">
</a>
Since this is done dynamically, how can I with jquery fadeIn or slideUp the ".portfolio-item-details" if the href is equal to the ID. Basically thumbnail with "#portfolio1" should slide up the div with "#portfolio1" on click.
This is my jquery code which to add the IDs and HREF is working perfectly but not working to slideUp or fadeIn the div with the same ID.
$(document).ready(function () {
var i=0;
$(".portfolio-item-details").each(function(){
i++;
var newID="portfolio"+i;
$(this).attr("id",newID);
$(this).val(i);
});
var i=0;
$(".open-portfolio-item-details").each(function(){
i++;
var newReadMoreHREF="#portfolio"+i;
$(this).attr("href",newReadMoreHREF);
$(this).val(i);
if ($(".portfolio-item-details").attr("id") == "newReadMoreHREF") {
$(this).fadeIn();
}
});
});
SOLUTION
Thanks to Austin's code, I was able to modify it to work with mine.
Check here: http://jsfiddle.net/jdoimeadios23/xpsrLyLz/
You want something like this?
HTML
<div class="image" value="1">
<img src="thumbnail.jpg" />
</div>
<div id="portfolio1" class="details">details</div>
<div class="image" value="2">
<img src="thumbnail.jpg" />
</div>
<div id="portfolio2" class="details">more details</div>
JS
$(document).ready(function () {
$('.details').fadeOut(1);
$(".image").click(function () {
var num = $(this).attr("value");
$("#portfolio"+num).fadeIn(1000);
});
});
JSFiddle Demo
You don't even need to bother with ID's so long as the next div below each image is it's details.
The problem is in this block
if ($(".portfolio-item-details").attr("id") == "newReadMoreHREF") {
$(this).fadeIn();
}
Because you're having two errors, the first one is that newReadMoreHREF is a variable, not a string in your HTML or a value to any variable and so on.
Second thing is, that in the variable declaration you're using "#portfolio"+i;, which would be good if you were about to select an element. But using it in the jQuery iif statement with .attr('id') will again cause a havoc.
The thing that you need is something like this
$(".open-portfolio-item-details").each(function(){
i++;
var newReadMoreHREF="portfolio"+i; // removed #
$(this).attr("href",newReadMoreHREF);
$(this).val(i);
if ($(".portfolio-item-details a").attr("id") == newReadMoreHREF) {
// you need to access the hyperlink in the element, not
// the element itself. this portfolio1 ID is of a hyperlink
// again here, this is referencing the main iterator.
$(this).fadeIn();
// are you sure you want to fade the .open-portfolio-item-details?
}
});
Removed the hash sign and then called the variable value to check against. It would execute to be true if the condition is true.
Try this:
HTML:
content
<section id="portfolio2" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio2" title="">
<img src="thumbnail.jpg">
</a>
<div id="portfolio1" class="portfolio" hidden>Portfolio 1</div>
<div id="portfolio2" class="portfolio" hidden>Portfolio 2</div>
Jquery:
$('a.open-portfolio-item-details').on('click', function (e) {
e.preventDefault();
var id = $(this).attr('href');
$('.portfolio').hide();
$('.portfolio' + id).fadeIn();
});
Couldn't get the fiddle link for some reason.
Edit:
I don't know the name of the class that shows the content you want displayed, so as an example I'm using portfolio. Try putting this code into a fiddle

Checking div.contents() for presence of another div

I have a piece of javascript which allows for the selection of multiple choices. An example of the html is this:
Pick an option:
<br><br>
<div id="dialogue_container"> </div>
<div id="Append"> And then this happens.</div>
<div class="inlinechoice-0" id="0">
<a class="question" id="1">Choice 1</a><br>
<a class="question" id="2">Choice 2</a><br>
<a class="question" id="3">Choice 3</a>
</div>
<div class="answer-1">
You picked 1.
<div class="inlinechoice-1" id="1">
<a class="question" id="4">Choice 4</a><br>
<a class="question" id="5">Choice 5</a><br>
</div>
</div>
<div class="answer-2">
You picked 2.
</div>
<div class="answer-3">
You picked 3.
</div>
<div class="answer-4">
You picked 4.
<div class="inlinechoice-2" id="2">
<a class="question" id="6">Choice 6</a><br>
<a class="question" id="2">Choice 7 (2)</a><br>
</div>
</div>
<div class="answer-5">
You picked 5.
</div>
<div class="answer-6">
You picked 6.
</div>
<br><br>
<FORM>
<INPUT TYPE="button" onClick="history.go(0)" VALUE="Refresh">
</FORM>
Then I have some javascript here:
$('div[class*=inlinechoice').on('click','.question', function(e) {
var $this = $(this),
$id = $this.prop('id');
$("#dialogue_container").append($('.answer-' + $id).contents());
});
$('div[class*=inlinechoice').on('click', function(a) {
var $this = $(this),
$cid = $this.prop('id');
$('.inlinechoice-' + $cid).hide();
});
And then a little bit of CSS here:
div[class*='inlinechoice-'] { cursor: pointer; }
div[class*='answer-'] {display:none}
div[class*='append']{display:none}
The way it works is that all of the inlinechoice/answerclass/append class begin as hidden. As the user clicks the options, the javascript puts the appropriate answers into the dialogue_container div in the order that they are selected. However, I would like to add a final touch, and that is to show the contents of the append div once there are no more choices available to the user. I need to check the contents of the dialogue_container to see if there are any active inlinechoices(i.e. non hidden ones), and if there are none, then I can set the append div to be shown. I'm thinking the solution will be something like suggested here, but I'm not sure how to apply this to the contents of the dialogue container, as they are dynamic.
Thanks.
Codepen here
Edit: New Codepen here. I've added the following code to the first question onclick event and it's appending correctly to choices which have no nested choices (i.e. choices 2 and 3) in them, but not choice 1 (which has additional questions). I think rather than searching the entire contents of #dialogue_container, I need to just look at the contents of the last select #answer, however, this is proving a bit tricky.
$foo = $("#dialogue_container").append($('.answer-' + $id).contents());
$str = $foo.html();
$term = "question";
$index = $str.indexOf($term);
if($index != -1){
//Do Nothing
}
else{
$('#append').show();
}
Edit: Is there a particular reason why this works:
$foo = $("#dialogue_container").append($('.answer-' + $id).contents());
But this doesn't?
$('.answer-' + $id).contents();
I'm guessing it's something to do with using .contents() combined with a class rather than a div, but I'm not sure how to instruct the script to return just the contents of the last clicked answer class.
If I add the following in, I can get an alert to return the correct contents, but I don't want to hardcode the answer-id class like this:
alert($('[class*="answer-2"]').eq(0).html());
I've tried:
alert($('[class*="answer-"]' + $id).eq(0).html());
To try and pick up the correct answer class, but it doesn't return anything. I feel like I'm nearly there on this, but not quite!
Edit: Thanks to a little clarification here, I finally managed to figure this out! I'll add the answer below.
Missing ] in your attribute selector
$('div[class*=inlinechoice]').on('click', '.question', function(e) {
// -----^-----
var $this = $(this),
$id = $this.prop('id');
$("#dialogue_container").append($('.answer-' + $id).contents());
});
$('div[class*=inlinechoice]').on('click', function(a) {
// -----^-----
var $this = $(this),
$cid = $this.prop('id');
$('.inlinechoice-' + $cid).hide();
});
CODEPEN
So it turns out that the order in which I called things mattered (you'd think I'd be able to figure something like this out by now).
Adding the following into the javascript right after $id variable has been defined seems to have done the trick:
//This is the append code which adds the contents of the append div when there are no more choices.
$str = $('.answer-' + $id).html();
$index = $str.indexOf("question");
if ($index != -1) {
//Do Nothing
} else {
$('#append').show();
}
Codepen

how to hide/remove all text in-between two elements?

lets say i have this lump of HTML:
<div class="container">
<span class="title">Heading 1</span>
This is a description..<br />
This is the second line..
<div class="image"><img src="image.jpg" /></div>
</div>
What i want to do using jQuery/JavaScript is hide/remove all text and elements between <span class="title"> and <div class="image">.
I've looked all over and found pretty much nothing. Any ideas on how i could do this?
How about something like this? http://jsfiddle.net/ZW8q2/1
var foo = $('.container').children(':not(br)');
$('.container').html('').html(foo);
You could try:
var str = $('.container .title').text() + $('.container .image').html();
$('.container').html(str);
JS Fiddle.
Try this:
Place a tag around what you want to hide, give div an ID name. So in the end your will look like:
<div id = "hideMe" style ="display:block">...Your Content...</div>
Use this javascript:
function hide()
{
document.getElementById('hideMe').style.display = "none";
return;
}
Have the Javascript function called whenever you want to hide the stuff between the div from a button (or other control) like this:
<input type= "submit" onclick ="hide()">

Categories