using .replaceWith() jQuery - javascript

I have a div that has this elements:
<div id = "menu">
<a>Elemento1</a><br/>
<a>Elemento2</a><br/>
<a>Elemento3</a><br/>
</div>
Each time one of the elements gets clicked I want a new div with different content to be added beside this list, depending on which element is clicked, it should add a diferent list. I'm new to web development, and I found that using the jQuery function .replaceWith() may do it, but is there any way I can use this function, adding divs I got in other .html files?
Thanks!

To get a certain part of another HTML file, use jQuery load function. A basic usage in your case, would be:
$('#result').load('ajax/test.html #container_you_want_to_load');
To add an element after or before the link, you have a few choices. The question is if you really need it. Perhaps it's enough to define one target div into which you'll load your content. In that case, the above example would suit perfectly.
If you however want to add element next to <a> tag, consider using after or before jQuery functions.
To catch a click even on one of your links, check click

Why not just have <div id="content"></div> after the menu, then use
$("#content").load("your_file.html");?

replaceWith is used to replace some DOM elements with different ones. I don't think this function can solve this.
You can use .load function to get html files content and insert it wherever you want. Just bind a click event to every link and use their href atributtes to get the respective file. Don't forget to return false in the end of the event.
something like this:
<div id="menu">
Elemento1
Elemento2
Elemento3
</div>
<div id="content"></div>
$("#menu a").click(function(){
$("#content").load(this.href);
return false;
});

Related

adding a new section on webpage using only css and js

I am trying to click on an image on my webpage and it open a new section on the page that would be created in css and javascript/jquery. I thought about using .addclass() but i am not entirely sure how to go about it. Can anyone give me an example of this being done?
An example by clicking on a element with the id foo and adding a div with the id bar after that element:
$("#foo").click(function(){
$(this).after('<div id="bar">Some content</div>');
});
Of course, there are multiple methods in jQuery which insert content somewhere in the DOM tree, see:
https://api.jquery.com/category/manipulation/dom-insertion-outside/
https://api.jquery.com/category/manipulation/dom-insertion-inside/
There are many ways to do it. As an example, you can simply attach a click event handler to your image, like so:
$('img').click(newSection);
function newSection() {
$('#someDiv').append('<div class="newSection"></div>');
}

how to toggle a div on click at different div?

I am trying to toggle a div by clicking on a different div. The only relation that two divs share is that they are inside the same div. I have a DIV class comment which holds DIV class button that is supposed to toggle DIV class box when clicked. The box DIV is also inside the comment DIV. I am trying to use jQuery(this).find(".box").toggle();, but it is not working. I am triggering it with $( ".button" ).click(function(). The script is currently at the bottom of my body.
Could anyone please tell me what am I doing wrong here? I've been playing around with the function for a while now, but with no luck at all. Thank you in advance for your replies.
JSFIDDLE here
HTML
<div class="comment">
<div class="button">
show/hide .box with text1
</div>
<div class="box">
text 1
</div>
</div>
<div class="comment">
<div class="button">
show/hide .box with text2
</div>
<div class="box">
text 2
</div>
<div>
jQuery
$( ".button" ).click(function() {
jQuery(this).find(".box").toggle();
});
You can use the jQuery selector .siblings() to re-write your function like this:
$( ".button" ).click(function() {
$(this).siblings().toggle();
});
Here's a working fiddle to demonstrate.
All you really need to do is this:
$(this).parent().find(".box").toggle();
In short, change:
jQuery(this).find(".box").toggle();
To ONE of the following lines:
$(this).parent('.comment').find(".box").toggle();
$(this).closest('.comment').find(".box").toggle();
$(this).siblings(".box").toggle();
Full Explanation:
The reason it's not working is due to the call. Let's break down your call and see what exactly it's doing.
First we see a simple jQuery selector. This tells jQuery to look for a div containing the class button. Keep in mind, jQuery makes use of any CSS selector. So selecting an item in jQuery is as simple as using it's CSS selector!
$( ".button" )
Next you are assigning an event. In this case, that event is click, meaning you're telling a div having the class button to do something every time it is clicked. Keep in mind, however, not including a callback function is an easy way to trigger this event as well.
$( ".button" ).click(function() {
Now this next line is where your mistake takes place.
jQuery(this).find(".box").toggle();
The first mistake is the use of jQuery. after you're already making use of it's short sign, $. You only need use the elongated name if you are using jQuery's noconflict because another JS library you include might use $. In other words, if $('.button') works and is a jQuery object when used, then you don't need to use jQuery.. See more about this here.
Now, that aside, we can look at jQuery(this) as $(this). Whenever you use $(this) in an Event's callback method, you're referring to the element that the event was tied too. That means that $(this) in your function refers to $('.button'). The problem here is that you then want it to find an inner element containing the class box. Well according to your HTML, that can't happen since .box is a sibling, it is not within the inner HTML of .button. Thus you need to make a different call before you can find .box.
There are actually several solutions here. No solution is more "correct" than another, just simply different and possibly causes a different amount of "time" to run. Now I went with what I saw as being the most simple in that it gives you control over the parent element which contains ALL relevant elements to this function. I'll talk about possible alternatives in a minute.
$(this).closest('.comment')
The above line simply tells .button:clicked to look for the first parent element that contains the class .comment. In other words, this won't find any children or siblings, it will only go up from the current element. This allows us to grab the block that contains all relevant elements and information and thus make maneuvers as needed. So, in the future, you might even use this as a variable in the function, such as:
$('.button').click(function(e) {
var container = $(this).closest('.comment');
Now you can find anything within this element block. In this case you want to find box and toggle it. Thus:
$(this).closest('.comment').find(".box").toggle();
// Or with our variable I showed you
container.find(".box").toggle();
Now, there are plenty of alternatives based on your HTML layout. This example I've given would be good even if .box was buried inside more elements inside .comment, however, given your exact HTML, we see that .button and .box are siblings. This means that you could make this call different entirely and get the same result using something like:
$(this).siblings(".box").toggle();
This will allow our currently clicked and selected button element to look for ANY and ALL siblings having class box. This is a great solution and simple if your HTML is that simple.
However, many times, for "comment" type setups, our HTML is not so simple, nor is it static. It's usually something loaded after the page load. This means our general assignment of .click will not work. Given your exact HTML and not knowing a static Parent ID, I would probably write your code as:
$(document).on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
What this does is allow for this click event to be assigned to ANY element containing .button for a class, whether loaded with page or even ten minutes after the page is up. However, the caveat often seen here is the assignment is placed on document. Should we assign a lot of events to document it could become quite convoluted and possibly slow down the client's browser. Not to mention the arguments held over all the other headaches this could cause. So here's my recommendation, make a static (loads with page, is a part of page's main HTML) loading area and do our dynamic assignment to that. For instance:
<div id"Comments"><!-- load comments --></div>
Then you can do the assignment as such:
$('#Comments').on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
If you have any more questions, just comment!
Side Note .on is for jQuery versions 1.7+. If using older jQuery, use .live or .bind

jQuery: I see append, prepend, appendTo, what about take-out-the-content-of?

I see all sorts of jQuery options such as append, prepend, appedTo etc. but I just want to take out the content of a div and append it to the inside of the body. The whole contents, so not by using .html() but being loads of other divs. These divs may have events attached as well so I don't want to mess them all up.
<div id="main">
<div id="anything" class="anything">
<p>hello etc.</p>
</div>
</div>
So I need to take out everything inside id="main"
So, something like $('#main').get-its-contents-and-append-to('body') would do it.
I guess I could write a lengthy script, but there must be a simple one-line jQuery option?
Something like this:
$('#main').detach().children().appendTo('body');
Omit the .detach() part if you want to leave the #main div in place but empty.
This will retain any event handlers or data associated with the elements being moved, as you can see here: http://jsbin.com/iguqew/1/edit
You should be able to use append:
$("body").append($("#main").html());
$("#main").empty();
You could also do this which should keep the event handlers in place:
$('body').append($("#main").children());

Run jQuery function onclick

so i implemented a bit of jQuery that basically toggles content via a slider that was activated by an <a> tag. now thinking about it id rather have the DIV thats holding the link be the link its self.
the jQuery that i am using is sitting in my head looks like this:
<script type="text/javascript">
function slideonlyone(thechosenone) {
$('.systems_detail').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).slideDown(200);
}
else {
$(this).slideUp(600);
}
});
}
</script>
i was using this as a index type box so there are several products when you click on the <a> tag that used to be an image* it would render a bit of content beneath it describing the products details:
<div class="system_box">
<h2>BEE Scorecard database</h2>
<p>________________</p>
</div>
the products details are wrapped in this div.
<div class="systems_detail" id="sms_box">
</div>
so when you click on what used to be a image* it would run the slideonlyone('div_id_name') function. the function above then first closes all the other divs with the class name 'system details' and then opens/slides the div with the id that was passed into the slideonlyone function. that way you can toggle products details and not have them all showing at once.
note i only kept the <a> tag to show you what was in there i will be getting rid of it.
note: i had an idea of just wrapping the whole div in an <a> tag but is that good practice?
So now what i am wondering is since you need JavaScript to run onclick on a div tag how do you write it so that it still runs my slideonlyone function?
Using obtrusive JavaScript (i.e. inline code) as in your example, you can attach the click event handler to the div element with the onclick attribute like so:
<div id="some-id" class="some-class" onclick="slideonlyone('sms_box');">
...
</div>
However, the best practice is unobtrusive JavaScript which you can easily achieve by using jQuery's on() method or its shorthand click(). For example:
$(document).ready( function() {
$('.some-class').on('click', slideonlyone('sms_box'));
// OR //
$('.some-class').click(slideonlyone('sms_box'));
});
Inside your handler function (e.g. slideonlyone() in this case) you can reference the element that triggered the event (e.g. the div in this case) with the $(this) object. For example, if you need its ID, you can access it with $(this).attr('id').
EDIT
After reading your comment to #fmsf below, I see you also need to dynamically reference the target element to be toggled. As #fmsf suggests, you can add this information to the div with a data-attribute like so:
<div id="some-id" class="some-class" data-target="sms_box">
...
</div>
To access the element's data-attribute you can use the attr() method as in #fmsf's example, but the best practice is to use jQuery's data() method like so:
function slideonlyone() {
var trigger_id = $(this).attr('id'); // This would be 'some-id' in our example
var target_id = $(this).data('target'); // This would be 'sms_box'
...
}
Note how data-target is accessed with data('target'), without the data- prefix. Using data-attributes you can attach all sorts of information to an element and jQuery would automatically add them to the element's data object.
Why do you need to attach it to the HTML? Just bind the function with hover
$("div.system_box").hover(function(){ mousin },
function() { mouseout });
If you do insist to have JS references inside the html, which is usualy a bad idea you can use:
onmouseover="yourJavaScriptCode()"
after topic edit:
<div class="system_box" data-target="sms_box">
...
$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });
You can bind the mouseenter and mouseleave events and jQuery will emulate those where they are not native.
$("div.system_box").on('mouseenter', function(){
//enter
})
.on('mouseleave', function(){
//leave
});
fiddle
note: do not use hover as that is deprecated
There's several things you can improve upon here. To start, there's no reason to use an <a> (anchor) tag since you don't have a link.
Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.
I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?
== EDIT ==
The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.
http://jsfiddle.net/THEtheChad/j9Ump/

Making only a div visible inside an iFrame

I have an iFrame in a html page myPage.html where I am displaying another page otherPage.html. otherPage.html is a complicated page with many elements. I want to display only one div in the iFrame. All the others should remain hidden. How can I do this?
Instead of the iFrame, I tried to use the .load() function in jQuery. But for some reason, the page does not load. The otherPage.html is served from an IIS server and the page is constructed from purely Javascript. I have no idea why nothing is loading when I use the load() function.
How would I go about achieving this?
Update:
Here are some clarifications:
I tried to use the .load() function on myPage.html. Anyway, after fiddling around, I found the following to work:
For the div that I want to show, I hide all its siblings and also hide all the siblings of its parent. The following jQuery statement seems to do this:
$("#myFrame").contents().find("#chart1").show().parentsUntil('body').andSelf().siblings().hide();
I have only one issue now. When I do the following:
Load myPage.html in Firefox (It also loads otherPage.html in an
Iframe)
Manually open firebug and type
$("#myFrame").contents().find("#chart1").show().parentsUntil('body').andSelf().siblings().hide();
it seems to hide everything else.
But then I want to automate it. In other words, when I load myPage.html I want it to load the contents of the iFrame. Once the iFrame contents are loaded I want to then run this script:
$("#myFrame").contents().find("#chart1").show().parentsUntil('body').andSelf().siblings().hide();
I cannot get this to work. I have tried these two approaches so far:
$(document).ready(function() {
$("#myFrame").ready(function () {
$("#myFrame").contents().find("#chart1").show().parentsUntil('body').andSelf().siblings().hide();
});
});
I have also tried to use
$("#myFrame").load(function () {
instead. But in both these cases the script does not hide the other elements. Since, the script works when I use it manually in the console, I assume that somehow it is running before all the elements are loaded. Please give me your thoughts.
Hide everything within the iFrame by something like $("#myIFrame *").hide(); or you can set the css display property to none.
Using CSS selector, re-display only the div you want. If your div has an id this is pretty easy : $('#myDiv').show();
If the div does not have an id, see if you can give it one. If creating an id for your div is not an option, try to give its parent an id/class.
If ID is not an option you may also find selectors like :nth-child() useful.
You say you are using the load() function. Are you using this in the parent page or the iframe page? Do you really mean to use the ready() function instead?
$(document).ready(function(){
// some code here ...
});
Using ready() on the document will ensure that the DOM elements have completely loaded, and then will execute the code in the handler. Without more information I'm not sure I can help much with what you're trying here.
Using an iframe you should first remember that if you want only one div to be visible and all others to be hidden you must make sure that the "visible" div is not inside an "invisible" container. If the container is hidden, all children will be hidden too.
If you had a div "showme", then something like this would work:
<div id="showme">visible text</div>
<div style="display:none;">hidden text</div>
But doing it this way, everything would be hidden:
<div style="display:none;">
hidden text
<div id="showme">supposed to be visible, but hidden!!</div>
</div>
If you are changing the visibility, or display, of an element you can do it in the iframe page like this:
// using jQuery...
// set the display css to an empty string, defaulting to visible (not 'none')
$('#showme').css('display','');
// set other elements to be hidden...
$('#hideme1').css('display','none');
$('#hideme2').css('display','none');
$('#hideme3').css('display','none');
If you want to change the visibility of elements from the PARENT page you first access the iframe, then change the elements within it:
// using jQuery...
// get the iframe. ps. you dont have to put the $ in front of the variable name.
// I chose to do it this way to remind myself it's a jQuery object.
var $f = $('#myiframe').contents();
// set the display css to an empty string, defaulting to visible (not 'none')
$f.find('#showme').css('display','');
// set other elements to be hidden...
$f.find('#hideme1').css('display','none');
$f.find('#hideme2').css('display','none');
$f.find('#hideme3').css('display','none');
See this article for example(s) on working with elements in a child iframe:
http://www.computerhowtoguy.com/jquery-and-iframes/
As I understood your question. You can do like this, pass div id to get displayed as hash in your otherPage.html url like you have a div with id first, you can pass first as hash
<iframe src="otherPage.html#first" />
and in otherPage.html, you can get this hash and according to that show your div, but make first all your sections hidden, using css will be easy, only add "display:none;" in css.
and try this : in otherPage.html
$(function(){
//var divToShow = location.hash.subString(1);
//$('#'+divToShow).show();
var divToShow = location.hash;
$(divToShow).show();
});

Categories

Resources