javascript does not want to parse text more than twice - javascript

So i have this function in my Js that gets called on a link onclick() event.
here is the HTML:
<li class="collapsed">
<span>
Directions
</span>
<p>ajajgajajys agajgjgtajgtdja ajdtajtjate ajgdjagjd ajt</p>
</li>
And here is the Javascript:
function expand(myElem)
{
if (myElem.parentNode.parentNode.style.height<100)
myElem.parentNode.parentNode.style.height="100px";
else
myElem.parentNode.parentNode.style.height="45px";
}
Obviosuly, the code expands the li parent tags that the links are in. Originally, the li tags are set as height:45px; in CSS. Then they change to 100px and back.
The problem im having is that the javascript only works twice.
I cna click on the links oncde and expand the li's. Then i can click on them and collapse the li's. Then it doesn't want to work again.
I was looking at my browsers errors and i found this:
"Error parsing value for 'height'. Declaration dropped.
After much trolling thru the interwebs I thought it might be because i'm not including the unit declarations in my js. But I am!
myElem.parentNode.parentNode.style.height="45px"; ---- as you can see.
****NOTES: MY SOLUTION*****
For future referance for whoever stumbles on this thread, here's my solution:
HTML --> I ened up doing somethin glike:
<span class="heading">
Link1
<span>
<span class="information">
Info about Link1
</span>
<span class="heading">
Link2
<span>
<span class="information">
Info about Link2
</span>
And the Jquery was super simple:
$(document).ready(function() {
$(".information").hide();
$(".heading").click(function(){
var item = $(this);
item.next().slideToggle(500);
});
});
...super simple, works like a charm

Try to use replace and parseInt functions like,
function expand(myElem)
{
if (parseInt(myElem.parentNode.parentNode.style.height.replace('px','')) < 100)
myElem.parentNode.parentNode.style.height="100px";
else
myElem.parentNode.parentNode.style.height="45px";
}
You can use Jquery for simplifying it like,
HTML
<li class="collapsed">
<span>
Directions
</span>
<p>ajajgajajys agajgjgtajgtdja ajdtajtjate ajgdjagjd ajt</p>
</li>
SCRIPT
$(function(){
$('.direction').on('click',function(e){
var ht= $('.collapsed').height()==100 ? 45 : 100;
$('.collapsed').height(ht);
});
});

Try
if (parseInt(myElem.parentNode.parentNode.style.height)<100)

Thank you everyone for your help.
I was able to figure out that, for some reason, after the height was set the second time around to 45px, it wasn't registering as a int anymore. idk y tho. Why would it accept a declaration of 100px the first time and register it as int but not the second time? wierd.
Anyway, i tried parseInt and it worked like a charm.
But I really like the jQuery solution that Jason P provided. the transition sold me. I'm gonna go with that.
So thanks again guys.

Related

Why I cant get to hidden article by putting url with hashname?

I have been looking for solution, but i don't find anything, that would suit me. I got a page with header and content divs. Content div is not visible. After clicking on item in nav menu, I want to hide header, and show chosen article. I achieved it, but when I try to get to article by url#name nothing happens.
"jsfiddle" wont be useful in this case, but i will paste it to show my code.
Is there different way to do it? Maybe somehow hide articles with code, then just change opacity, maybe use "addclass" from jquery? I don't really know, im mixed and stuck.
Thanks for help.
https://jsfiddle.net/edby86ta/8/
You can also do it in full css :
https://jsfiddle.net/edby86ta/11/
In this case, the hardest part is hiding it again. You'd have to have a "close" button directing to another (maybe nonexistant) anchor :
Close
You can apply very simple JS conditions to show and hide your articles based on the link, I`ve updated you JSfiddle.
https://jsfiddle.net/edby86ta/10/
$(function () {
//GET HASH FROM URL, CHECK IF ELEMENT EXISTS AND THEN SHOW IT
$(document).ready(function(){
var hash = window.location.hash;
if(hash.length){
$(hash).show();
}
})
$(".article-nav a").on("click", function () {
$(".main-article").hide();
console.log($(this).attr("id"));
$('#article-' + $(this).attr("id")).show();
});
});
article {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<nav>
<ul class="article-nav">
<li><a id="1" href="#article-1">Article 01</a></li>
<li><a id="2" href="#article-2">Article 02</a></li>
</ul>
</nav>
</header>
<div id="content">
<article id="article-1" class="main-article">Article 01 Lorem ipsum</article>
<article id="article-2" class="main-article">Article 02 Lorem ipsum</article>
</div>
<footer></footer>
Advice: Be aware that the user can change the hash as he wants, injecting anything to your selector, you should check the hash before using it.

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

Remove style attribute from all descendants in jquery

I'm brand new to javascript/jquery, but have been going okay so far (though you'd hate to see my code), but I've hit a wall with trying to strip out style tags from some HTML I'm trying to clone.
The reason for cloning is that the CMS I'm forced to use (which I don't have access to code behind, only able to add code over the top) automatically builds a top nav, and I want to add a duplicate sticky nav once the user scrolls, but also add a couple of elements to the scrolled version.
The original HTML of the top nav looks a bit like like:
<nav id="mainNavigation" style="white-space: normal; display: block;">
<div class="index">
Participate
</div>
<div class="index" style="margin-right: 80px;">
News
</div>
<div class="index active" style="margin-left: 80px;">
<a class="active" href="/about/">About</a>
</div>
<div class="external">
Collection
</div>
<div class="index">
Contact
</div>
</nav>
I had mild success (other than those style tags I want to remove) with the following, even though it doesn't seem to make sense to me, as I expected some of the elements would be repeated (the whole < nav >…< /nav > tag should have been within the #mainNavigation clone, no?):
var originalNavItems = $('#mainNavigation').clone().html();
$("#site").prepend('
<div id="ScrollNavWrapper">
<div class="nav-wrapper show-on-scroll" id="mainNavWrapper">
<nav id="newScrolledNav" style="white-space: normal; display: block;">
<div class="index home">
Home
</div>
' + originalNavItems + '
<div class="newItem">
<a href="http://www.externalsite.com">
View on External Site
</a>
</div>
</nav>
</div>
</div>');
I've tried to use a few answers from related questions on here, but I keep getting incorrect results. Can you help me?
You can strip the style elements like so:
var el = $('#mainNavigation'); // or whatever
el.find('[style]').removeAttr('style');
You can use
var originalNavItems = $('#mainNavigation').clone().find("*").removeAttr("style");
Then you can use .append() to add that html elements
Fiddle
You can clone into an imaginary div and then fetch the mainNavigation also. You can also remove the style attributes along with that. Hope this works for you...
var temp = $('<div />').html($('#mainNavigation').clone());
temp.find('*').removeAttr('style');
originalNavItems = temp.html();
The nav is cloned but the html() function only returns the HTML for the contents and that's why it disappears. You can avoid some string manipulation by adding the cloned element directly before a target element.
$("#site").prepend('
<div id="ScrollNavWrapper">
<div class="nav-wrapper show-on-scroll" id="mainNavWrapper">
<nav id="newScrolledNav" style="white-space: normal; display: block;">
<div class="index home">
Home
</div>
<div class="newItem">
<a href="http://www.externalsite.com">
View on External Site
</a>
</div>
</nav>
</div>
</div>');
$('#mainNavigation').clone()
.find('[style]').removeAttr('style').end()
.insertBefore('#newScrolledNav .newItem');
In the previous case find('[style]') matches elements that have a style attribute.
I'm new to Stack Overflow (and js in general), so this might be really bad ettiquette, but I seem to have accidentally fixed it myself trying to debug my implementation of the first upvoted answer that #Anoop Joshi gave above. Please comment and let me know if it would have been better to just edit my question!
I decided to break the process down into separate steps – similar to #Kiran Reddy's response actually, but I hadn't got to trying his yet.
I tried:
var styledHTML = $('#mainNavigation').clone();
styledHTML.find("div[style]").removeAttr('style');
var originalNavItems = styledHTML.html();
$("#site").prepend('<div… etc.
with a console.log(styledHTML) etc under each line to check what I had at each stage – and it worked! (The code did, console.log didn't?)
I was just doing this to try and log the value of the variables at each stage, but whatever I did fixed it…
Now I need to figure out why I can't even make console.log(variable); work :-/
Try this code
$('#mainNavigation').children().removeAttr('style');
Hope this will help you.

Is there a way to add an element to the same height as another selected element dynamically?

I am new to front-end development. I was trying to code an annotation tool. A sample screen is shown on the image below. After the user select a sentence, an annotation box appears on the right side bar at the same horizontal position as the highlighted sentence. Any ideas about how I can achieve that effect?
Here is my html structure. I used the framework of Zurb Foundation:
<section id="main">
<div class="row">
<div class="small-8 large-8 columns"id="rawdata">
<p> <span class="sentence">2:22 So, last time I was here, I don't know if I told you this, but, um, we kind of did a "I like, I wish" activity on paper, about things that you like about studio, and things that you wish would change.</span><span class="sentence"> Um, do you want to share any of those thoughts now, so maybe we can talk about them? [name], I have yours if you want to look at it again.</span></p>
<p><span class="sentence">2:47 I forgot to add something.</span></p>
<p><span class="sentence">2:54 Well, I don't know, in terms of what I dislike about studio.</span></p>
<p><span class="sentence">2:57 So, some people wrote in theirs that, um, they dislike how cluttered it gets.</span></p>
<p><span class="sentence">5:09 I don't get bothered.</span>< <span class="sentence">I like the draftiness, I'm a little...</span><span class="sentence"> I'm one of the ones that opens the windows, and like—</span></p>
</div>
<div class="small-4 large-4 columns" id="annotations"><p></p>
</div>
</div>
</section>
JS for selecting sentence and adding annotations:
<script>
$('.sentence').click(function() {
$(this).toggleClass('sentenceStyle');
var y = $(this).offset().top;
var para = document.createElement("p");
$("#annotations").append(para);
para.innerHTML="this is an annotation";
para.css("position",'absolute');
para.style.top = y;
});
</script>
And here it is the fiddle: http://jsfiddle.net/yujuns/HDe6v/3/
There are some things that you want to change in your code.
First what you want is to get the offset of the selection. That can only happen if you put an html tag around the selection and then get its offset. You can then place an absolute positioned message box by setting its left and top offset to the offset you got from html element.
In the following fiddle, I have shown a basic implementation to give you the basic idea. Hope it helps.
Fiddle
EDIT:
Try this fiddle update.(In response to author's question). I have added comments to lines of code that I added to js. I also added position: relative to css for annotations
Updated Fiddle

jQuery: get a reference to a specific element without using id

I'm tinkering a bit with jquery to show a hidden div when a link is clicked. This should be fairly simple, but there's a flaw to it in this case. I have the following markup:
<div class="first-row">
<div class="week">
<p>Uge 2</p>
<p>(08-01-11)</p>
</div>
<div class="destination">
<p>Les Menuires</p>
<p>(Frankrig)</p>
</div>
<div class="days">4</div>
<div class="transport">Bil</div>
<div class="lift-card">3 dage</div>
<div class="accommodation">
<p><a class="show-info" href="#">Hotel Christelles (halvpension)</a></p>
<p>4-pers. værelse m. bad/toilet</p>
</div>
<div class="order">
<p>2149,-</p>
<p class="old-price">2249,-</p>
</div>
<div class="hotel-info">
<!-- The div I want to display on click -->
</div>
</div>
When I click the "show-info" link I want the "hotel-info" div to display.
My backend devs don't want me to use ids (don't ask me why..) and the above markup is used over and over again to display data. Therefore I need to be able to access the "hotel-info" div in the "first-row" div where the link is clicked.
I've tried to do something like:
$(document).ready(function() {
$('.show-info').click(function() {
var parentElement = $(this).parent().parent();
var lastElementOfParent = parentElement.find(".show-hotel");
lastElementOfParent.show();
});
});
But without a result :-/ Is this possible at all?
Any help is greatly appreciated!
Thanks a lot in advance!
Try this:
$('.show-info').click(function() {
$(this).closest('.accommodation').siblings('.hotel-info').show();
});
Even better imo, as it would be independent from where the link is in a row, if every "row div" has the same class (I assume only the first one has class first-row), you can do:
$(this).closest('.row-class').find('.hotel-info').show();
Reference: .closest, .siblings
Explanation why your code does not work:
$(this).parent().parent();
gives you the div with class .accommodation and this one has no descendant with class .hotel-info.
It is not a good idea to use this kind of traversal for more than one level anyway. If the structure is changed a bit, your code will break. Always try to use methods that won't break on structure changes.
You're right in not using an ID element to find the DIV you want :)
Use closest and nextAll
Live demo here : http://jsfiddle.net/jomanlk/xTWzn/
$('.show-info').click(function(){
$(this).closest('.accommodation').nextAll('.hotel-info').toggle();
});

Categories