www.webdeveloper.com
Results 1 to 6 of 6

Thread: optimizing script and passing parameters to function

  1. #1
    Join Date
    Feb 2011
    Location
    London
    Posts
    62

    optimizing script and passing parameters to function

    HI there, I wonder if you can help me. I am doing a bit of javascript/jquery testing here and there and I have come up with the following http://antobbo.webspace.virginmedia.com/test/test.htm. Now first thing, you will notice when you land on the page that for less than a second you will see a big yellow div appearing and disappearing. This is the first issue. I have a div more_info that I hide away through jquery:

    HTML Code:
    ...
    <div id = "more_info" class = "more_info">
    
    						<p>info on Item 1</p>
    						<p>info on Item 2</p>
    						<p>info on Item 3</p>
    						<p>info on Item 4</p>
    						<p>info on Item 5</p>
    						<p>info on Item 6</p>
    						<p>info on Item 7</p>
    						<p>info on Item 8</p>
    						<p>info on Item 9</p>
    					</div>
    ...
    Code:
    ...
    .more_info
    	{
    		border:1px solid red;
    		width:400px;
    		height:400px;
    		position:absolute;
    		left:900px;
    		top:300px;
    		/*display:none;*/
    		background-color:yellow;
    	}
    ...
    and the script:
    Code:
    ...
    function no_script(){
    var info_div = document.getElementById('more_info');
    info_div.style.display = "none";
    
    
    $("#navigation li a").hover(
    	function(){
    	$(".more_info").css("display","block");
    	}, function(){
    	$(".more_info").css("display","none");
    	}
    	);
    
    }
    ...
    The function in the external script is called from the body tag in the html. Is this the reason why the div appears briefly when the page loads? How do I get around this and make sure that the div is hid straight away without flashing on my screen for a sec?

    Second issue: when I get the first one fixed, what I would like to do is to ideally hover on the first item in the right-hand side list (under "select a design") and get the yellow div up with just the corresponding paragraph: so first list item gets "info on Item 1", second list item gets "info on Item 2" etc... Now, what's the best way to achieve this? I presume I need to first hide all the paragraphs, then send them as parameters to the function and then show them again. So assuming each paragraph has a para id so that paragraph 1 is para1 etch would the following be correct
    HTML Code:
    <div id = "navigation">
    		<ul>
    			<li><a href = "#" onHover = "no_script("para1")">gdkjgkdf</a></li>
    			<li><a href = "#" onHover = "no_script("para2")">flkjgsldfgs</a></li>
    			...
    I am just trying to get a feeling for the best way to build or modify the attached script
    thanks

  2. #2
    Join Date
    Nov 2010
    Posts
    978
    the first issue has to do with the way your page loads. Think about it: the html loads first (including your yellow div). Then the javascript comes along and hides the div. The way you had it originally (with the div hidden in the css) makes more sense, as it hides the div before it is event created.

    For the second one, you need some way to reference which element is getting the onmouseover event and which needs to be shown as a result (there is no onhover event listener in classic javascript by the way - just two separate onmouseover and onmouseout listeners).

    You could do this by Id's or classes, but in these cases, where there are a set number of list items corresponding to the same number of divs to be shown, you can find out which li is getting mouseover'ed, get the number of that and use it to show the correspondingly numbered div

    you are also mixing jQuery and plain javascript, which they say is a bad idea... I don't know why as jQuery is javascript, but anyway. None of what you are trying to do is that complicated in plain js, so I give you an example like that - it wouldn't be so hard to put it into jQuery if that's what you really want but like I say, there's no point to it and really you should learn how javascript works before starting on jQuery as many people using jQuery get confused as to the very basics of the javascript that underlies it.

    also note that here the event listeners are taken out of the html and added by the javascript in a loop - this is fashionable at the moment, but I do it in this case because it's easier than writing the same thing 9 times

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <style>
    #navigation
    	{
    		float:left;
    	}
    	
    #more_info
    	{
    		border:1px solid red;
    		width:400px;
    		height:400px;
    		float:right;
    		display:none;
    		left:900px;
    		top:300px;
    		background-color:yellow;
    	}
    
    #more_info p
    	{
    	display:none;
    	}
    	</style>
    </head>
    <body>
    <div id = "navigation">
    		<ul>
    			<li><a href = "#">Li 1</a></li>
    			<li><a href = "#">Li 2</a></li>
    			<li><a href = "#">Li 3</a></li>
    			<li><a href = "#">Li 4</a></li>
    			<li><a href = "#">Li 5</a></li>
    			<li><a href = "#">Li 6</a></li>
    			<li><a href = "#">Li 7</a></li>
    			<li><a href = "#">Li 8</a></li>
    			<li><a href = "#">Li 9</a></li>
    </div>			
    <div id = "more_info">
    						<p>info on Item 1</p>
    						<p>info on Item 2</p>
    						<p>info on Item 3</p>
    						<p>info on Item 4</p>
    						<p>info on Item 5</p>
    						<p>info on Item 6</p>
    						<p>info on Item 7</p>
    						<p>info on Item 8</p>
    						<p>info on Item 9</p>
    					</div>
    
    <script type="text/javascript">
    var lists=document.getElementById("navigation").getElementsByTagName("a");
    var ps=document.getElementById("more_info").getElementsByTagName("p");
    var shown;
    
    for (var i = 0; i < lists.length; i++) {
    lists[i].onmouseover=function(){no_script(this) }
    lists[i].onmouseout=hide;
    lists[i].onclick=function(){return false; }
    	}
    
    function no_script(which){
    document.getElementById("more_info").style.display="block"
    for (var i = 0; i < lists.length; i++) {
    if(lists[i]==which){
    ps[i].style.display="block"
    shown=ps[i];
    break;	
    		}
    	}
    }
    
    function hide(){
    document.getElementById("more_info").style.display="none"
    if (shown){
    shown.style.display="none";
    	}
    }
    </script>
    </body>
    </html>

  3. #3
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,633
    and one else with JQ :-))

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Test</title>
    <base href="http://antobbo.webspace.virginmedia.com/test/">
    <link rel="stylesheet" type="text/css" href="style.css">
    <style type="text/css">
    #more_info{display:none;}
    </style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
    //script.js - everything deleted
    var all_images=new Array (
    	"animal_full_1.jpg",
    	"animal_full_2.jpg",
    	"animal_full_3.jpg",
    	"animal_full_4.jpg",
    	"animal_full_5.jpg",
    	"animal_full_6.jpg",
    	"animal_full_7.jpg",
    	"animal_full_8.jpg",
    	"animal_full_9.jpg",
    	"animal_full_10.jpg",
    	"animal_full_11.jpg",
    	"animal_full_12.jpg"
    );
    function anim(k){
    if(k==all_images.length){k=0;}
    $('#preloader').html('');
    $('#preloader').append('<img src="'+all_images[k]+'" alt=""  />');
    k++;
    $('#preloader img').load(function(){
    $('#the_image').fadeOut('slow',function(){
    $(this).attr('src',$('#preloader img').attr('src'));
    $(this).fadeIn('slow',function(){setTimeout('anim('+k+')',2500);});
    });
    });
    }
    //script_navigation.js - everything deleted
    $(document).ready(function(){
    $('body').append('<div id="preloader" style="display:none"></div>');
    // let's set the id attribute for each p inside more_info
    $('#more_info p').each(function(i){$(this).attr('id','p_'+i);});
    $('#navigation li a').each(function(i){
    // let's set the id attribute for each a inside navigation
    $(this).attr('id','a_'+i);
    $(this).mouseover(function(){
    // find the numeric part of this id attribute
    var n=$(this).attr('id').replace(/a_/,'');
    $('#more_info').css('display','block');
    $('#p_'+n).css('display','block');
    $('#p_'+n).siblings().css('display','none');
    });
    $(this).mouseout(function(){$('#more_info').css('display','none');});
    });
    setTimeout('anim(1)',2500);
    });
    </script>
    </head>
    <body>
    		<div id="wrapper">
    
    			<div id="image_div">
    				<img src="animal_full_1.jpg" alt="" id="the_image">
    			</div><!-- end of image_div -->
    
    			<div id="para">
    				<p>Download the sample html file and css file</p>
    			</div><!-- end of content -->
    
    			<div id="text_wrap">
    					<div class="text_image">
    
    					</div><!--end of title -->
    
    					<div id="navigation">
    						<ul>
    							<li><a href="#">link 1</a></li>
    							<li><a href="#">link 2</a></li>
    							<li><a href="#">link 3</a></li>
    							<li><a href="#">link 4</a></li>
    							<li><a href="#">link 5</a></li>
    							<li><a href="#">link 6</a></li>
    							<li><a href="#">link 7</a></li>
    							<li><a href="#">link 8</a></li>
    							<li><a href="#">link 9</a></li>
    						</ul>
    					</div>
    
    					<div class="text">
    
    						<p>Littering a dark and dreary road lay the past relics of browser-specific tags, incompatible DOMs, and broken CSS support.
    
    Today, we must clear the mind of past practices. Web enlightenment has been achieved thanks to the tireless efforts of folk like the W3C, WaSP and the major browser creators.
    
    The css Zen Garden invites you to relax and meditate on the important lessons of the masters. Begin to see with clarity. Learn to use the (yet to be) time-honored techniques in new and invigorating fashion. Become one with the web.
    
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras leo est, tincidunt at dapibus at, ultricies id diam. Duis metus diam, malesuada non sodales sed, suscipit non tortor. Donec sed sem at mi mattis vestibulum. Aliquam ultricies felis id diam convallis iaculis. Donec suscipit sagittis dignissim. Cras tortor magna, facilisis ac cursus et, suscipit ut mauris. Morbi ut nisl elit. Etiam sed urna risus, in vulputate odio.
    
    Sed vulputate egestas iaculis. Duis ac nisl nibh, sit amet sodales arcu. Donec tincidunt, purus eget vulputate ornare, leo ante egestas turpis, quis molestie dolor mi eget dui. Vestibulum hendrerit pretium gravida. Aliquam erat volutpat. In et dolor eros. Vestibulum felis enim, facilisis at auctor quis, pellentesque id orci. Cras nec odio sed metus tempor feugiat. Aliquam tincidunt aliquam ante, ut condimentum purus dictum eget.
    </p>
    
    					</div><!-- end of text -->
    
    					<div id="more_info" class="more_info">
    
    						<p>info on Item 1</p>
    						<p>info on Item 2</p>
    						<p>info on Item 3</p>
    						<p>info on Item 4</p>
    						<p>info on Item 5</p>
    						<p>info on Item 6</p>
    						<p>info on Item 7</p>
    						<p>info on Item 8</p>
    						<p>info on Item 9</p>
    					</div>
    
    					<div class="text_image">
    
    					</div><!--end of text_image -->
    
    					<div class="text">
    						<p>
    						Ut at justo sed justo luctus scelerisque. In lectus urna, consectetur quis scelerisque vitae, suscipit ut nisi. Vestibulum dapibus eros ut dolor sodales mollis a sit amet est. Mauris eget dui sed nisi tincidunt sollicitudin at ut metus. In hac habitasse platea dictumst. Fusce sit amet diam est. Curabitur vulputate placerat hendrerit. Cras ultrices mollis elit, quis venenatis diam pretium nec. Aliquam at dui a odio semper tempor placerat vitae nisi.
    						</p>
    					</div>
    
    					<div id="clearing">
    
    					</div>
    
    			</div><!-- end of text_wrap-->
    
    
    
    		</div><!-- endnof wrapper -->
    
    	</body>
    
    </html>
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  4. #4
    Join Date
    Feb 2011
    Location
    London
    Posts
    62
    xelawho, thanks for helping me with this.
    for the first point, the reason why I hid the div is because I want it to be visible to people with javascript off. So it the div is hidden they will see it, if javascript is on instead they will get it by hovering on the list. So, say I want to keep it visible, is there a way I can make sure it stays hidden when the page is loaded?
    For the javascript instead. Sorry, it was very slack of me not to check the syntax first, I got confused with jquery and attempted to add a bit of javascript to it, hence onhover rather than onmouseover and not.
    Thanks for posting the code but my javascript isn't that advanced, so I am afraid I need to ask you for a bit of an explanation if it isn't too much of a trouble sorry.
    The first few lines of your script:
    Code:
    var lists=document.getElementById("navigation").getElementsByTagName("a");
    var ps=document.getElementById("more_info").getElementsByTagName("p");
    I have never seen this before. Does it mean that the variable lists contains “#navigaton a”so all the links within the navigation div and that the variable ps contains “#more_info p” so all the paragraphs within the more_info div?
    Code:
    lists[i].onmouseover=function(){no_script(this) }
    the this keyword I presume represents the current li hovered on which then gets passed to the no_script function;
    HTML Code:
    lists[i].onclick=function(){return false; }
    this returns false because we don’t want the link to be followed when the list item is clicked;
    HTML Code:
    function no_script(which){
    This is quite unclear. As far as I know “which” is a reserved word pretty much like “this”. SO here we are passing “this ” to the function, so I assume “which” is in place of “this”?

    HTML Code:
    if(lists[i]==which){
    ps[i].style.display="block"
    in here we are basically saying: if the current list item is equal to the parameter passed to the function, then hide the corresponding paragraph. But what do these 2 lines do
    HTML Code:
     shown=ps[i];
    break;
    the rest is ok.
    thanks

  5. #5
    Join Date
    Nov 2010
    Posts
    978
    Quote Originally Posted by js_newbie_80 View Post
    xelawho, thanks for helping me with this.
    for the first point, the reason why I hid the div is because I want it to be visible to people with javascript off. So it the div is hidden they will see it, if javascript is on instead they will get it by hovering on the list. So, say I want to keep it visible, is there a way I can make sure it stays hidden when the page is loaded?
    kind of. maybe there is a faster way to hide a div, but this is the fastest I can think of, put at the top of the head:
    Code:
    <script type="text/javascript">
    var timer=setInterval(check,1);
    
    function check(){
    if (document.getElementById("more_info")){
    document.getElementById("more_info").style.display="none";
    clearInterval(timer);
    		}
    }
    </script>
    ... basically, we're saying "as soon as the browser sees this, start running a function every 1 millisecond that checks if there is such a thing as this div and if there is, hide it then stop checking".

    which gives interesting results. In FF, I don't see it at all. In Chrome I get a yellow flash. In IE I see a fraction of the div about 2 times out of 5.

    so that's that. I must say you're very conscientious catering for people with javascript turned off. For me, they're such a minority who must be used to web pages not working that I kind of forget about them...

    as to your other questions...
    Code:
    var lists=document.getElementById("navigation").getElementsByTagName("a");
    var ps=document.getElementById("more_info").getElementsByTagName("p");
    "I have never seen this before. Does it mean that the variable lists contains “#navigaton a”so all the links within the navigation div and that the variable ps contains “#more_info p” so all the paragraphs within the more_info div?"

    yes. it returns a collection (which is kind of like an array) that can be referenced by index

    Code:
    lists[i].onmouseover=function(){no_script(this) }
    "the this keyword I presume represents the current li hovered on which then gets passed to the no_script function;"

    correct.

    HTML Code:
    lists[i].onclick=function(){return false; }
    "this returns false because we don’t want the link to be followed when the list item is clicked;"

    correct.

    HTML Code:
    function no_script(which){
    "This is quite unclear. As far as I know “which” is a reserved word pretty much like “this”."

    Not as far as I am aware. "which" doesn't appear on the ecmascript list of reserved words. It may be reserved in some browser, but the code I gave you works fine in FF, IE and Chrome.

    "SO here we are passing “this ” to the function, so I assume “which” is in place of “this”?"

    yes. you could just as well replace "which" with "blerg" as long as you did it consistently.

    HTML Code:
    if(lists[i]==which){
    ps[i].style.display="block"
    "in here we are basically saying: if the current list item is equal to the parameter passed to the function, then hide the corresponding paragraph. But what do these 2 lines do"
    HTML Code:
     shown=ps[i];
    break;
    you will notice that there is a global variable
    Code:
    var shown;
    at the top of the script. in the no_script function it takes the value of whatever div got shown, and then at the start of the hide function we say "if this variable is defined (which come to think of it, it always will be, but anyway) hide it"

    the other option would be to loop through all of those divs and hide them all - but what's the point? 8 out of 9 are already hidden and we know which one just got shown, so...

    all break does is stop the loop from continuing - we know that there's only ever going to be one match, so once that's made, the rest of the loop is useless.

  6. #6
    Join Date
    Feb 2011
    Location
    London
    Posts
    62
    fab thanks

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles