Prepend dynamic content to multiple elements with jQuery - javascript

Sure this is an easy one but finding it hard to search for an answer due to not knowing the exact words to search for :/
also if theres a better way of doing this please do tell me ;)
basically I'm generating some div boxes with various contents and titles
so in my html pages I have:
<div class="itdSec" data-title="What is This">
This is a magical div box with some stuff in it
</div>
in my js file I have
$(".itdSec").prepend("<div class='itdSecTit'>" + this.data("title") + "</div>");
The intent is to add a div to the top of that div with the contents of the data-title arribute
the "this" is causing the errors as this is still the main page. and using $(".itdSec") in its place returns the first one each time.

This works:
$(function(){
$(".itdSec").prepend(function() {
return "<div class='itdSecTit'>" + $(this).data("title") + "</div>";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="itdSec" data-title="What is This">
This is a magical div box with some stuff in it
</div>
alternatively you can do this:
$(function(){
$(".itdSec").each(function() {
$(this).prepend("<div class='itdSecTit'>" + $(this).data("title") + "</div>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="itdSec" data-title="What is This">
This is a magical div box with some stuff in it
</div>

With $('.itdSec') you are selecting all elements with the class .itdSec, however, prepend only works on one element.
What you need to do is use jQuery's .each() to iterate over all the selected elements and prepend the title for every single element.
$('.itdSec').each(function(i) {
// 'i' is the index (0,1,2,3...) - not needed here
// 'this' is now every element in turn
var title = $(this).data('title');
$(this).prepend('<div class="itdSecTit">' + $(this).data("title") + '</div>');
});
(JSFiddle)
Inside the .each() loop you can then use this as the element that is currently being iterated over.

Related

How to add to the content of a div without deleting it's original content using javascript

I was making a quiz site and when I came to the point when I was making a button to show you the correct answer of your mistake I used document.getElementById but it always erased the rest of the answers that was written by the same method.
here is a snippet of my javascript code
if (mistakes > 0) {
if (document.getElementById('wrongAnswer1').checked === true ||
document.getElementById('wrongAnswer2').checked === true) {
document.getElementById('mistakesDiv').innerHTML =
document.getElementById('mistakesDiv').innerHTML +
"<br>" +
"question 1's correct answer is" +
document.getElementById('correctAnswer1').value;
}
}
Design your html div as:
<div id="contentId">
......
......
</div>
And your javascript like:
var div = document.getElementById('contentId');
div.innerHTML += 'your content';
You can separate the content which you are adding dynamically from existing content because when you are updating innerHTML it will update all the content inside the selected element.
So one solution is take a parent div(the div which you will select for adding new child) and add child divs(dynamically added div) inside that for each correct answer.
If you want to give some id to dynamic div you can use a counter or question id for which this new child div has got added.
For adding new children to "parent" you can use "appendChild" method.
It will be something like this:
<div id="parent">
<div id="child1">Here goes the correct answer</div>(button element will also work fine)
</div>
I have created a fiddle for your scenario please have a look:
https://jsfiddle.net/jbw7ku15/
In order to append without changing the actual html, for example you want to give the user the ability to add fields to a form that he is in process of filling. You can use insertAdjacentHTML
var html = "<br>" + "question 1's correct answer is" + document.getElementById('correctAnswer1').value;
document.getElementById('mistakesDiv').insertAdjacentHTML("afterend",html);

javascript click image display

What I'm trying to do is, when one of six divs is clicked, a separate div will have 3 specific divs appear in it. Each of the original six divs have three similar but different divs related to it.
http://jsfiddle.net/petiteco24601/hgo8eqdq/
$(document).ready(function () {
$(".talkbubble").mouseout(function(){
$(".sidebar").show();
});$
$(".talkbubble").click(function(){
$
How do I make it so that when you click a "talkbubble" div, a different "sidebar" div appears with all its contained elements, and when you mouseout, the first talkbubble div automatically activates?
Here is a demo of how to do this: http://jsfiddle.net/n1xb48z8/2/
The main part of this example is some javascript that looks like this:
$(document).ready(function(){
showSideBar(1);
$('.expander').click(function(){
var sidebarIndex = $(this).data('sidebar-index');
showSideBar(sidebarIndex);
});
$('#Container').mouseleave(function(){
showSideBar(1);
});
});
function showSideBar(index){
$('.sidebarContent').hide();
$('.sidebarContent[data-index="' + index + '"]').show();
}
.data('some-name') will get you the attribute data-some-name="" on the specific element, this is a html 5 attribute and if you do not want to use it you can instead give each of the elements their own class names such as:
<div class="sidebarContent subBarContent_1">
<!-- content -->
</div>
and use the '.subBarContent_1' as your jquery selector instead. You would then also have to have some sort of data attached to your clickable divs to identify which one you wanna show, you could use a hidden field to do that like:
<input type="hidden" class="subContentSelector" value="subBarContent_1" />
The javascript for that looks like this:
$(document).ready(function(){
showSideBar(1);
$('.expander').click(function(){
var sidebarSelector = $(this).find('.subContentSelector').val();
showSideBar(sidebarSelector );
});
$('#Container').mouseleave(function(){
showSideBar('subBarContent_1');
});
});
function showSideBar(selector){
$('.sidebarContent').hide();
$('.sidebarContent.' + selector).show();
}
Ps. the overflow:hidden css is because chrome was messing up the placement of the sidebar content otherwise... oh chrome, you silly goose

Update multiple elements with html from jquery ajax call

I have an AJAX call which returns multiple HTML fragments that need replacing on the page:
<div data-replace="some-div">
<p>whatever</p>
</div>
<div data-replace="some-other-div">
<p>something else</p>
</div>
Currently I am adding all the html to a hidden div on the page and then doing:
hiddenDiv.find('[data-replace]').each(function () {
$('#' + $(this).data('replace')).html($(this).html());
$(this).remove();
});
which seems to work but seems a bit hacky.
Is there a better way (whilst still returning HTML rather than JSON as this is out of my control)?
I would create a jQuery object with all DOM elements and not append them to the document as an hidden DIV element since you don't need it. Also you won't need to remove it after your update.
Something like this:
(assuming that your AJAX response is a variable called data)
var $data = $("<div>" + data + "</div>");
$data.find('[data-replace]').each(function () {
$('#' + $(this).data('replace')).html(this.innerHTML);
});

How to use jquery with variable assigned

How can I use a variable in jQuery. as you see in script snippet, I assign a variable "divname" with value, and when i use 'Jquery" to fade out. it is not working. What I really need is, when image is hover, the description will be show up as fading in, when mouse is gone, the the description should be gone. thanks in advance.
Script snippet
$j('.img_nofade').hover(function(){
$j(this).animate({opacity: .5}, 300);
var i = $j(this).attr('titlename');
var divname = "'#titleID" + i + "'";
//alert (divname);
$j(divname).fadeIn();
},
function(){
$j(this).animate({opacity: 1}, 300);
$j(divname).fadeOut();
}
);
HTML code
<img class="img_nofade' src="image-1.gif" titleid='1" />
<div id="titleID1">my image title 1 </div>
<img class="img_nofade' src="image-2.gif" titleid='2" />
<div id="titleID2">my image title 2 </div>
<img class="img_nofade' src="image-3.gif" titleid='3" />
<div id="titleID3">my image title 3 </div>
No need to use the ' char, just:
var divname = "#titleID" + i;
And in the hover's handlerOut function, the divname is already out of scope, you should define it again.
There are a few issues I see.
Your attributes in your HTML are mixing single and double quotes. You need to use one or the other.
$j(this).attr('titlename'); - The attribute name doesn't match your HTML attributes. (titlename vs titleid)
You have a scoping issue with the var divname. You define it in your mouseover event which means it won't be defined in your mouseleave event. You should just use the next method to get a reference to your div. $j(this).next().fadeIn() This would prevent the need for trying to find the titleID in the first place.
There are a few issues here.
1) You have some typos in the HTML. Be careful about single and double quotes. Not all browsers will automatically correct those kinds of errors, and if Javascript can't find the HTML it's looking for, then your code will break.
2) jQuery provides some excellent resources for getting elements without having to fall back on the varname-style thing (i.e. var titleId = $(this).attr('titleId')+i;)
Instead, you can do something like this:
<img class="img_nofade" src="image-1.gif"/>
<div class="description">my image title 1 </div>
<img class="img_nofade" src="image-2.gif"/>
<div class="description">my image title 2 </div>
<img class="img_nofade" src="image-3.gif"/>
<div class="description">my image title 3 </div>
I got rid of the titleId attribute and changed the divs from id="TitleID1" to "description". It's more generic, but it's also more semantic from a styling standpoint. You won't have to individually style each of those things.
The jQuery would look something like:
$('.img_nofade').hover(function(){
$(this).animate({opacity: .5}, 300);
$(this).next('.description').animate({opacity: 0}, 300);
},function(){
$(this).animate({opacity: 1}, 300);
$(this).next('.description').animate({opacity: 1}, 300);
});
The $.next() method grabs the next element. If you pass in a selector, you can grab the next element with that selector. This is really useful when you're dynamically adding things to the page and want to grab the next one on the list. There are several other ways to do this, this just happens to be the easiest in this scenario, I think.
Finally, you should keep in mind that the .fadeIn() and .fadeOut() methods will change the display attribute to display:none when hiding. This means that in your above example, without any styling, the titles would disappear, causing the images to slide together. That's why I chose to animate on the opacity instead. You can definitely do the fadeIn/fadeOut thing if you have CSS styling those images to keep them from collapsing in on each other.
Good luck.
You have two functions for the hover and have declared divname in the first and then you are trying to use it in the second. This won't work because it is not in scope of the second function.
Instead of using the divname in this case you could use $j(this).next() to select the next sibling, in this case the div following the img and call fadeIn() and fadeOut() that way.
$j('.img_nofade').hover(function(){
$(this).next().fadeIn();
}, function(){
$(this).next().fadeOut();
});
This isn't too hard
$j('.img_nofade').hover(function(){
var title = 'titleID' + $(this).attr('titleid');
$('#' + title).fadeIn();
}, function(){
var title = 'titleID' + $(this).attr('titleid');
$('#' + title).fadeOut();
});
Try this fiddle
http://jsfiddle.net/cmyks/

jQuery: load method reload same div in div?

i'm a little confused.
i want to actually reload the same page and fetch a div with a certain id from it. so i'm trying to reload a part of website into the same part of the website. ;) i know it sounds weird.
somehow i don't get what i'm doing wrong or better how i have to do it.
var $sv = $('#server_view');
$sv.load('/server/ftp/' + goToURL + " #server_view");
so in this case the same div gets loaded into the same div and that's not what i want.
it then looks like:
<div id="#server_view"> <div id="#server_view"> blabla</div> blabbla </div>
i actually just want to grab the contents of the div inside and reload them. how can i solve this little problem.
You can grab the children with the selector you're passing to .load(), like this:
var $sv = $('#server_view');
$sv.load('/server/ftp/' + goToURL + " #server_view>*");
All we're doing different is getting all direct children to insert using the > child selector.
use .get and replace the element
$.get('/server/ftp/' + goToURL, function(response){
var newContent = $(response).find('#server_view').html();
$('#server_view').replaceWith( newContent );
});
Simple end fast.
$( "#content" ).load( "# #content>*" );
if you are using $('#server_view');, you must have DIV ID as server_view, not #server_view

Categories

Resources