Replacing div with another on click - javascript

My knowledge of javascript is close to none and I'm trying to have a div be replaced on click by another div.
<div class='replace-on-click'>
<h1>Click to Insert Coin</h1>
<div class='replaced-with'>
<div class='info-text'>
<h1>Title</h1>
<h2>Subtitles</h2>
</div>
<ul class='info-buttons'>
<li><a href='#' class='b1'>Buy Tickets</a></li>
<li><a href='#' class='b2'>Find Hotels</a></li>
</ul>
</div>
</div>
I'd like it so when you click "Click to Insert Coin", that will disappear and make the .replaced-with div take its place, hopefully with some kind of fade transition if possible. How do I go about doing this?

We will make use of jQuery because it helps us to get you desired behavior done in a few statements. So first include jQuery from somewhere in your head part of your HTML document.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Then somewhere include this Javascript code (e.g. create index.js and include it the way like the library code).
$(document).ready(function() {
$('h1').click(function() {
$(this).fadeOut(function() {
$('.replaced-with').fadeIn();
});
});
});
It does the following: When your document is ready, it adds an event handler on h1 waiting for clicks. On click, it first fades out the h1 and when it's done, it fades the other element in.
In your HTML document, include the hidden attribute to the object that should be hidden initially.
<div class='replaced-with' hidden>
Here you can find it working as well: http://jsbin.com/cuqoquyeli/edit?html,js,console,output

Related

After appending content from localStorage to div scripts doesn't work anymore

When page loads my code reads LocalStorage and retrieves saved value. Then it appends that value to DIV element within page.
Thus far it works, but clicking on sort-link-css elements won't trigger script. If I remove appended DIV and use original code, then all scripts work perfectly.
HTML in beginning:
<div id="thisclone">
// Lot of code
</div>
Setting variable in LocalStorage:
$('.region-checkboxes').click(function(e) {
var menu = $("#thisclone").html();
localStorage.menu = menu
});
HTML that is saved in LocalStorage:
<div class="row select-row" style="margin-bottom:5px !important;">
<div class="sort-link-css" id="to-hide" style="background: url("/assets/blue-up.png") 93px 11px no-repeat;">
<a class="sort_link desc" data-method="get" data-remote="true" href="http://www..eu/lv?q%5Bs%5D=height+asc">AUGUMS</a>
<span class="num">1</span>
</div>
<div class="sort-link-css" style="background: url("/assets/down.png") 93px 11px no-repeat;">
<a class="sort_link" data-method="get" data-remote="true" href="/lv?q%5Bs%5D=age+desc">VECUMS</a>
<span class="num">0</span>
</div>
<div class="sort-link-css" style="background: url("/assets/down.png") 93px 11px no-repeat;">
<a class="sort_link" data-method="get" data-remote="true" href="/lv?q%5Bs%5D=votes_for.size+desc">PATĪK</a>
<span class="num">0</span>
</div>
</div>
Then at the top of page I am reading localStorage and appending it to DIV:
<script>
var fromstorage = localStorage.getItem('menu');
$(fromstorage).appendTo(".menu-dupl");
</script>
Visually, newly appended div looks exactly like the starting one. But functionally, simple scripts doesn't work anymore.
Script example:
$('.sort-link-css > a').click(function(e) {
alert("Test");
});
This is just one script that doesn't work.But basically, every script associated to newly appended div doesn't work anymore. Script start to working again if I remove newly appended div and use original div.
I tried:
var fromstorage = localStorage.getItem('menu');
$(fromstorage).clone().appendTo( ".menu-dupl" );
But still the same problem.
Thanks in advance for any help.
After briefly reviewing your question, I've noticed the following:
$(fromStorage).appendTo(".menu-dupl");
I'm not overly concerned about this particular line because you stated that the menu renders correctly but I didn't notice this class while inspecting your code snippets
Potential issue with your script
$('.sort-link-css > a').click(function() { alert("Test") })
It is possible that jQuery is not able to find the right elements on the DOM
When you do this $('sort-link-css > a), you're stating that you want to bind this event on <a></a> elements that are direct children of .sort-link-css
Now the potential issue might come into play when you append the menu on to another element. It is possible that this operation is making it difficult for jQuery to correctly identify the correct selectors
Debugging
Could you try to log out the jQuery expression after you append the menu?
In chrome debugger console, enter the following after the page loads: $(".sort-link-css > a")
This should log out all of the matched elements. If it is undefined, try to rework your jQuery selector to correctly identify those elements

show/hide div with dyamically assigned class

I am dynamically assigning the div id based on the api call back data. For example I have a bunch of data returned which is appended to a div and I can assign the div id with a unique ip address. I have full control over what I can assign i.e. DIV id or class or whatever..
I have attached an example of what the output looks like and hopefully it will clarify what i am looking for.
What I want to be able to achieve is when an endpoint link is clicked, it will show the respective div and hide all other DIV data boxes.. The endpoint links can made clickable and i can add onclick scripts to them or whatever needs to be done
Whether we use the div id or class name i am not fussed.
This should work just fine.
Assign your div with a class, in the demo i'm using EndPoint. The onclick function will use the class to find the div element and hide it. Then it will use this the element used to trigger the function, target the div within that element and show it.
$('.EndPoint').on('click', function () {
$('.EndPoint').find('div').hide();
$(this).find('div').show();
});
.EndPoint div{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="EndPoint">
End Point [0]
<div><b>IP Address:</b> 216.12.145.20</div>
</div>
<div class="EndPoint">
End Point [1]
<div><b>IP Address:</b> 172.230.105.123</div>
</div>
<div class="EndPoint">
End Point [2]
<div><b>IP Address:</b> 206.204.52.31</div>
</div>
If you don't understand anything please leave a comment below and I will get back to you as soon as possible.
Edit - jQuery Append with onclick
var IPs=["216.12.145.20","172.230.105.123","206.204.52.31"];
//Foreach value in array
$.each(IPs, function(i,v) {
//Append to id:container
$('#container').append('<div class="EndPoint">End Point ['+i+']<div><b>IP Address:</b> '+v+'</div></div>');
});
$('.EndPoint').on('click', function () {
$('.EndPoint').find('div').hide();
$(this).find('div').show();
});
.EndPoint div{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
I hope this helps. Happy coding!
Since elements are dynamically generated it's better to do with classes IMO.
HTML
<div id="endpoint1">
<a href='#' class='clicker'>End Point 1</a>
<p class='hideThis'>1.1.1.1</p>
</div>
<div id="endpoint2">
<a href='#' class='clicker'>End Point 2</a>
<p class='hideThis'>1.1.1.1</p>
</div>
<div id="endpoint3">
<a href='#' class='clicker'>End Point 3</a>
<p class='hideThis'>1.1.1.1</p>
</div>
JavaScript (using JQuery)
$('.clicker').on('click', function () {
$('.hideThis').hide();
$(this).next().show();
});
http://jsfiddle.net/ksvexr40/1
If you want to hide the content initially, just add the following CSS class which hides the content initially.
.hideThis{
display: none;
}

Navigation tab stay a certain color

I am using ASP.net and have a master page that utilizes navigation. My problem is when I click on a link it loads a different asp page, but the navigation tab doesn't switch to the clicked color,it reverts back to its original color. Since all the pages are loading the same, I can't just use CSS because the page is reloaded. Is there a way to write a javascript function that tells the page when it loads to display the hover color and keep it there? Since the only HTML I use is on the master page, I can't switch anything out. I'm sure there must be a way using nth-child but I can't figure it out. As for the code, a simple example is:
<div>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</div>
So how would I get the 2nd link to switch to the hover color when loading the page?
It's been a while since I've played with asp, so I won't have the exact terms, but I can point you in the right direction.
First, in your master page, add unique ids to all of your nav links. This will make it trivial to access those links in your specific asp pages. It helps to do this because otherwise it's hard to select the link you want. jQuery such as $("div ul li:nth-child('2')") will select the second li that's a child of a ul that's a child of div, but that could happen anywhere on your page.
Once you have that, let's assume your nav panel looks like this:
<div>
<ul>
<li id="linkOne">One</li>
<li id="linkTwo">Two</li>
<li id="linkThree">Three</li>
</ul>
</div>
Then, in the page that loads when Two is clicked, you need to add a script with an onLoad handler that modifies the link:
<script>
document.onload = function() { $("#linkTwo").addClass("hover"); };
</script>
This will wait till the document loads (otherwise you may try changing an element that doesn't exist yet), then run a function that finds the specific element with the id "linkTwo" and adds the css class "hover" to it.
Obviously, this line will be different for each specific asp page - or something you can have your server-side logic calculate.
Your question is a little unclear. But if i understood right in your case i should use a specific css class that is loaded if you determine that you are on current page.
Something like this (i don't know asp, i will put a general example)
<div>
<ul>
<li <?php if($CurrentPage = 'One') {echo 'class="active"';} ?>>One</li>
<li <?php if($CurrentPage = 'Two') {echo 'class="active"';} ?> >Two</li>
<li <?php if($CurrentPage = 'Three') {echo 'class="active"';} ?>>Three</li>
</ul>
</div>
this will put a special class to your element. That class will have the hover color, and the problem is solved.
Hope you can adapt this to asp.
Use the following:
html code
<body>
<div>
<ul style="display:inline; background-color:lightgray; float:left">
<li style="margin:20px; display:inline-block" onclick="frames['target'].location.href='one.html'; toggle_bgcolor(this);">One</li>
<li style="margin:20px; display:inline-block" onclick="frames['target'].location.href='two.html'; toggle_bgcolor(this);">Two</li>
<li style="margin:20px; display:inline-block" onclick="frames['target'].location.href='three.html'; toggle_bgcolor(this);">Three</li>
</ul>
<iframe id="target"></iframe>
</div>
</body>
JS function
function toggle_bgcolor(elem)
{
for(var c=0; c<elem.parentNode.getElementsByTagName('li').length; c++)
{
elem.parentNode.getElementsByTagName('li')[c].style.backgroundColor='';
}
elem.style.backgroundColor='limegreen';
}
The JS-block for the onclick event in each <li> element will toggle the baclkground-color of each <li> element when another <li> is clicked.
Check this fiddle

Adding Additional Div breaks Existing Jquery Code

I have a very simple div with an image inside:
<div class="stack4">
<img src="images/002m.jpg" width=200>
</div>
And a very simple Jquery function for when you hover over the image:
$(function () {
$('.stack4>img').hover(function(){
prompt('hello');
});
});
This all works fine. However, I'm trying to add additional content to the page, and so put the following HTML directly after the end of the first div:
<div id="menucontainer" class="menuContainer">
<div id="menu" class="menuContent">
<img src="images/003m.jpg" />
<img src="images/004m.jpg" />
</div>
</div>
After I add this, the jquery prompt no longer works. Why would adding anothing div break my existing javascript command like that?
There has to be a script error in the page that is causing a failure. Or there is a very slight chance that your new html in some way introduces an invisible element that covers your stack4 image. If you can provide a link somebody could debug it for you.
It breaks because the selector no longer matches any elements (because the class selector .stack4 does no longer match any element).
<div id="menucontainer" class="menuContainer">
<div id="menu" class="menuContent">
<img src="images/003m.jpg" />
<img src="images/004m.jpg" />
</div>
</div>
$(function () {
$('.stack4>img').hover(function(){
prompt('hello');
});
});
If you look at your javascript, it will:
match any child image of an element with class name stack4
Add a hover listener to each image
Display a prompt on hover.
IF you look at your updated DOM structure, class stack4 no longer exists. To make it work again, you have to replace this selector with your new equivalent, which would be the div with id=menu and class=menuContent.
Now, depending on your needs, you can target either #menu>img or .menuContent>img. If you go with the first one, the javascript fragment will only work for a single menu, with the id of menu. However, if you choose the second approach, any content with the class menuContent will have this functionality. So I'd go with:
$(function () {
$('.menuContent>img').hover(function(){
prompt('hello');
});
});

Wrapper with onclick takes priority over child with href

I have a wrapper box which has an onclick event to make the whole box cickable to go to a different page, something like this:
<div onclick="window.location='http://dom.com/page1/'">
<p>Title</p>
<img alt='img' />
<p>Some text</p>
My link
<p>Some more text</p>
</div>
The problem is that the child link will never go to page2 because the parent onclick takes priority and wherever you click on the box you will always end up in page1.
Is there any way to solve this, I need to be able to go to page1 when clicking anywhere on the box but going to page2 when clicking on the link.
The "onclick" handler is old-school. I'd recommend downloading and including jQuery in your HTML, then using it like so:
<script src="main.js"></script>
main.js:
jQuery( document ).ready(function(){
jQuery( "div" ).click( function( e ){
window.location='http://dom.com/page1/';
e.preventDefault();
};
} );
You probably don't need the e.preventDefault(); line, as you're changing the location of the browser before it executes.
Also, it's good practice to avoid applying click handlers to tags. Perhaps you should use two tags and CSS to properly position and layer to the two over-top each other.
You should look into event capturing and event bubbling. Here is a nice article to get you started.
One hack around it is to have anchor tag instead of div and make it block level element:
<a href="http://dom.com/page1/" style="display: block; text-decoration: none;">
<p>Title</p>
<img alt='img' />
...
</a>
This will also work when JS is disabled and the only downside is that it's not really elegant.

Categories