JavaScript; calling a function on pageload - javascript

All I want to do is to call this function while page is loading or after loading automaticly, I mean without hover or click or etc.
If I manage that I am going to put it in a for loop with a delay function in order to call bg1, bg2 bg3 and bg4 respectively
I have read so many questions all seem similar but somehow they don't work for me.
Could you please help me about it?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function slide()
{
$('#accordion > li.bg1')(
function () {
var $this = $(this);
$this.stop().animate({'width':'350px'},500);
$('.heading',$this).stop(true,true).fadeOut();
$('.bgDescription',$this).stop(true,true).slideDown(500);
$('.description',$this).stop(true,true).fadeIn();
}
),
function () {
var $this = $(this);
$this.stop().animate({'width':'115px'},1000);
$('.heading',$this).stop(true,true).fadeIn();
$('.description',$this).stop(true,true).fadeOut(500);
$('.bgDescription',$this).stop(true,true).slideUp(700);
}
});
</script>
<div id="content">
<ul class="accordion" id="accordion">
<li class="bg1">
<div class="heading">Heading</div>
<div class="bgDescription"></div>
<div class="description">
<h2>Heading</h2>
<p>Some descriptive text</p>
more ?
</div>
</li>
<li class="bg2">
<div class="heading">Heading</div>
<div class="bgDescription"></div>
<div class="description">
<h2>Heading</h2>
<p>Some descriptive text</p>
more ?
</div>
</li>
<li class="bg3">
<div class="heading">Heading</div>
<div class="bgDescription"></div>
<div class="description">
<h2>Heading</h2>
<p>Some descriptive text</p>
more ?
</div>
</li>
<li class="bg4">
<div class="heading">Heading</div>
<div class="bgDescription"></div>
<div class="description">
<h2>Heading</h2>
<p>Some descriptive text</p>
more ?
</div>
</li>
</ul>
</div>

First, try replacing the line $(function slide() with the usual wrapper $(document).ready(function() { and make sure that all your parentheses and braces are balanced correctly.
Second, your selector needs a method call, which you don't have. It's unclear what you want to happen -- do some of the HTML elements need to be hidden, then show up slowly? Or vice versa? Do you want it to toggle back and forth continuously? We can help you, but only if you're more specific about what problem you're trying to solve.
UPDATE
If you want to animate the list items in sequence, you need a few things. First, a setTimeout that calls your function from within itself after a delay. Second, use $('#accordion > li').eq(i) to pick out the ith list element, with i being incremented each time your function is called. And finally (and aesthetically), replace those fadeIn/fadeOuts with slideDown/slideUps so that the whole thing doesn't jerk and shift as it animates.
http://jsfiddle.net/mblase75/EJXRD/
function slide(i) {
var $this = $('#accordion > li').eq(i);
// $this.stop().animate({'width': '350px'}, 500); // not sure what this is meant to do
$('.heading', $this).stop(true, true).slideUp(500);
$('.bgDescription', $this).stop(true, true).slideDown(500);
$('.description', $this).stop(true, true).slideDown(500);
var $that = $this.siblings();
// $that.stop().animate({'width': '115px'}, 500);
$('.heading', $that).stop(true, true).slideDown(500);
$('.description', $that).stop(true, true).slideUp(500);
$('.bgDescription', $that).stop(true, true).slideUp(500);
var items = $('#accordion > li').length;
setTimeout(slide, 2000, (i+1) % items); // modulo
}
$(document).ready(function() { // start the loop at the top
slide(0);
});

$(function slide() is not valid syntax, you were probably looking for
$(function() {
as your first line

You can follow this order:
<html>
<head>
<script src="toLoadBefore.js"></script>
</head>
<body>
<div class="yourHTMLHere">
...
</div>
<script>
//the DOM is loaded you can start your JS code here
</script>
</body>
</html>

Related

Remove the parent div if child div is empty

I was trying to remove the whole parent div if it doesn't have the wc-gallery class on it. What I have in my script is the reverse of what I need. Basically it hide everything that has the wc-gallery on it.
SCRIPT:
// Additional Scripts
$(window).load( function() {
$(".gallery-container2 .gallery-item .wc-gallery").hide();
});
$(".gallery-container2 p").click(function() {
var id = $(this).data('id');
$("[data-id=" + id + "].gallery-item .wc-gallery").toggle()
});
$(function(){
$(".gallery-item").each(function(){
$(this).children('.wc-gallery').parents('.gallery-container2').hide();
});
});
Basically this will work fine if I Hide all the containers and display the child div afterwards though my content won't render due to script conflicts. Only way to solve this without conflict is to load first all of the containers then hide() or remove() them.
SCRIPT: (conflict due to onload content rendering)
$('.gallery-container2').hide();
$(function(){
$(".gallery-item").each(function(){
$(this).children('.wc-gallery').parents('.gallery-container2').show();
});
});
HTML: (1st set is the one should be visible 2nd set is the one that needs to be remove or hide.)
<ul>
<li><div class="gallery-container2">
<p data-id="1723"><strong>some text</strong></p>
<div class="gallery-item" data-id="1723">
<div class="wc-gallery" style="display: none;"></div>
</div>
</div></li>
<li><div class="gallery-container2">
<p data-id="2455"><strong>View before and after</strong></p>
<strong></strong>
<div class="gallery-item" data-id="2455">
<div><div></div></div>
</div>
</div></li>
</ul>
Loop through the '.gallery-container2' element and find out whether it has '.wc-gallery' children. if not hide the element.
$('.gallery-container2').each(function(){
var $this = $(this);
//find element with 'wc-gallery' class
var hasGallery = $this.find('.wc-gallery').length > 0;
if(!hasGallery){
$this.hide();
}
});
Pure JS you might do like this in ES6 terms.
var divsToHide = document.querySelectorAll("div div :not(.wc-gallery)");
for (var div of divsToHide) div.parentElement.parentElement.style.display = "none";
<div class="gallery-container2">
<p data-id="1723"><strong>some text</strong>
</p>
<div class="gallery-item" data-id="1723">
<div class="wc-gallery">first container</div>
</div>
</div>
<div class="gallery-container2">
<p data-id="1724"><strong>some text</strong>
</p>
<div class="gallery-item" data-id="1724">
<div>
<div>second container</div>
</div>
</div>
</div>
Try this. If div has children with class .wc-gallery than it will show the parent otherwise hide the parent.
$(function () {
$(".gallery-item").each(function () {
if($(this).children('.wc-gallery').length > 0)
$(this).parents('.gallery-container2').show();
else
$(this).parents('.gallery-container2').hide();
});
});

Jquery Dropdown List not sliding up after mouse leave

So I was basically trying to create a drop-down list with jquery. I was successful in achieving but came across with a slight problem. Here's the code
HTML
<div class="dropdown_heading">
text
</div>
<div class="dropdown_container">
<div class="">
Competition1
</div>
<div class="">
Competition2
</div>
<div class="">
Competition3
</div>
</div>
JQUERY
$(document).ready(function(){
$(".dropdown_heading").mouseenter(function(){
$(".dropdown_container").slideDown();
});
$(".dropdown_container").mouseleave(function(){
$(".dropdown_container").slideUp();
});
});
Once I hover over the dropdown_heading the dropdown shows-up and I'm able to navigate over it but the only way the it slides back up is if i actually have the cursor in the dropdown_container. If I try to slide it up removing the mouse from dropdown_heading, the dropdown is still visible. How would I be able to slide the submenu back up when the mouse leaves both div_container and div_heading?
I've tried to execute this function but therefore I am unable to navigate over the container. Thanks.
$(".dropdown_heading").mouseleave(function(){
$(".dropdown_container").slideUp();
});
You can try a timer based solution like
jQuery(function($) {
var $target = $(".dropdown_container");
$('.dropdown_heading').hover(function() {
clearTimeout($target.data('hoverTimer'));
$target.stop(true, true).slideDown(500);
}, function() {
var timer = setTimeout(function() {
$target.stop(true, true).slideUp();
}, 200);
$target.data('hoverTimer', timer);
});
$target.hover(function() {
clearTimeout($(this).data('hoverTimer'));
}, function() {
$(this).stop(true, true).slideUp();
});
});
.dropdown_container {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown_heading">
text
</div>
<div class="dropdown_container">
<div class="">
Competition1
</div>
<div class="">
Competition2
</div>
<div class="">
Competition3
</div>
</div>
The toggleClass() method toggles between adding and removing one or more class names from the selected elements.
This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect..
Try this,
$(document).ready(function(){
$(".dropdown_heading").mouseenter(function(){
$(".dropdown_container").toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown_heading">
text
</div>
<div class="dropdown_container">
<div class="">
Competition1
</div>
<div class="">
Competition2
</div>
<div class="">
Competition3
</div>
</div>

Turn off a function on mouseover - Javascript, jQuery

I am trying to create a content div with button links on a right sidebar. When the user is not hovering over any of the buttons, the content should rotate through each of the five button topics (I've accomplished this). Also, when the user hovers over a specific button, what should happen is a) stop the rotation and b) display only the content topic related to that button.
Currently all I can make it do is rotate through the topics (with a Javascript function) and make content appear and disappear on hover (in HTML). Help please?
<script>
function rotatecontent(){
curcontentindex=(curcontentindex<messages.length-1)? curcontentindex+1 : 0
prevcontentindex=(curcontentindex==0)? messages.length-1 : curcontentindex-1
futcontentindex=(curcontentindex==0)? messages.length-1 : curcontentindex+1
messages[prevcontentindex].style.display="none"
messages[curcontentindex].style.display="block"
messages[futcontentindex].style.display="none"
}
window.onload=function(){
if (document.all || document.getElementById){
getElementByClass("dyncontent")
setInterval("rotatecontent()", 1000)
}
}
$('#container li').hover(function() {
clearInterval(interval);
}, function() {
interval = setInterval("rotatecontent()", 1000);
});
</script>
HTML:
<body>
<ul id="container">
<li><a href="#">
<img src="image1.jpg" width="250" height="100" class="Bab-
image"></a></li>
<li><a href="#"><img src="image2.jpg" class="sluotr-image
</a></li>
<li><a href="#"><img src="image3.jpg"
class="blogs-image"></a></li>
<li><a href="#"><img src="image4.jpg" class="chat-
image"></a></li>
<li><a href="#"><img src="image5.jpg"
class="view-image"></a>
</li>
</ul>
<div class="dyncontent">
<div id="div1">Content 1</div>
<div id="div2" style="display:none">Content 2</div>
<div id="div3" style="display:none">Content 3</div>
<div id="div4" style="display:none">Content 4</div>
<div id="div5" style="display:none">Content 5</div>
</div>
</body>
</html>
Here's a jsfiddle rotates until you hover over one of the hyperlinks, then resumes when you leave: http://jsfiddle.net/58pms/11/ (updated jsfiddle, original only went through one rotation)
I feel like it's hard to say what's wrong with your original code since I had to add some variable declarations and HTML that were missing from your sample. I also took out the event handlers that would show the item you were hovering over for simplicity since I don't think that was your main question.
The HTML:
<ul id="container" overflow:hidden>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
<div class="dyncontent">
<div id="div1">Be A Billiken</div>
<div id="div2" style="display:none">Be A Billiken 2</div>
<div id="div3" style="display:none">Be A Billiken 3</div>
<div id="div4" style="display:none">Be A Billiken 4</div>
<div id="div5" style="display:none">Be A Billiken 5</div>
</div>
And the script:
var messages;
var curcontentindex = 0;
var prevcontentindex;
var futcontentindex;
var i;
function rotatecontent() {
messages.hide();
curcontentindex = (curcontentindex < messages.length - 1) ? curcontentindex + 1 : 0;
messages.get(curcontentindex).style.display = "block";
}
$(function() {
messages = $('.dyncontent').find('div');
i = setInterval(rotatecontent, 1000);
$('#container li').hover(function() {
clearInterval(i);
}, function() {
i = setInterval(rotatecontent, 1000);
});
});
Just declare the variable interval outside of window.onload function to make it a global variable (so it can be accessed by other functions), i.e.
var interval=0;
window.onload=function(){
// other code goes here
interval=setInterval(rotatecontent, 1000); // use the variable here
}
or make overall changes as follows
<script type="text/javascript">
function rotatecontent(){
// Your function's code here
}
$(document).ready(function(){
var interval=setInterval(rotatecontent, 1000);
$('#container li img').hover(function() {
clearInterval(interval);
}, function() {
interval = setInterval(rotatecontent, 1000);
});
}​);
</script>
Don't use window.onload when you're already using jQuery. Use
$(function() { } );
instead.

Javascript and jQuery to make divs into a tab based content page

I recently had a 30 min test for a job application using only Javascript with jQuery. Didn't have to be styled well or anything. I created a very basic "30 min" page with Javascript and jQuery which I thought was "ok".. I just wanted to get some feedback if there was a more efficient/better way of doing this? as it turned out, I didn't get the job.. always learning, and also the job was quite a way from where I live.
Anyway, the original HTML page given was as follows, and after that is my humble attempt to turn the basic HTML into a tab based content page - again within 30 mins.
<html>
<head>
<!-- stylesheet, javascript, etc. here -->
</head>
<body>
<h1>My Page</h1>
<h2 class="subheading">The first section</h2>
<div class="content">
<p>Lorem ipsum...</p>
</div>
<h2 class="subheading">The second section</h2>
<div class="content">
<img src="/some_image" alt="Image" title="Image"></img>
<p>Some other text</p>
</div>
<h2 class="subheading">The third section</h2>
<div class="content">
And some more text here
</div>
<div class="footer">
This is at the foot of the page
</div>
</body>
</html>
Ok, so my humble attempt is as follows:
<html>
<head>
<title>Test JS page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style type="text/css">
#tabs
{
width:457px;
height:60px;
}
#tab1, #tab2, #tab3
{
width:150px;
border:1px solid #ccc;
}
#tab1
{
float:left;
}
#tab3, #tab2
{
float:right;
}
#tab2_content, #tab3_content
{
display:none;
}
.clear
{
clear:both;
}
#content
{
height:300px;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('#tab1_link').click(function (e) {
e.preventDefault();
clearContent();
$('#tab1_content').show();
});
$('#tab2_link').click(function (e) {
e.preventDefault();
clearContent();
$('#tab2_content').show();
});
$('#tab3_link').click(function (e) {
e.preventDefault();
clearContent();
$('#tab3_content').show();
});
});
function clearContent() {
$("div[id*='_content']").each(function() {
$(this).hide();
});
}
</script>
</head>
<body>
<h1>My Page</h1>
<div id="tabs">
<div id="tab1"><a id="tab1_link" class="subheading">The first section</a></div>
<div id="tab2"><a id="tab2_link" class="subheading">The second section</a></div>
<div id="tab3"><a id="tab3_link" class="subheading">The third section</a></div>
</div>
<div class="clear">
</div>
<div id="content">
<div id="tab1_content" class="content">
<p>Lorem ipsum...</p>
</div>
<div id="tab2_content" class="content">
<img src="/some_image" alt="Image" title="Image"></img>
<p>Some other text</p>
</div>
<div id="tab3_content" class="content">
And some more text here
</div>
</div>
<div class="footer">
This is at the foot of the page
</div>
</body>
</html>
So as you can see, not pretty for sure.. the stylesheet was inline as is the script, however this was meant to be a test to show if you knew Javascript/jQuery enough to perform the tasks.. I figured it wasn't great, but not too bad either..
I would be grateful for any feedback on other ways to achieve the desired result.. again it doesn't have to be pretty, just functional.. and of course all within 30 mins..
Thanks!
<div id="tabs">
<ul>
<li>The First Section</li>
<li>The Second Section</li>
<li>The Third Section</li>
</ul>
<div id="tabs-1" class="content">
<p>Lorem ipsum...</p>
</div>
<div id="tabs-2" class="content">
<img src="/some_image" alt="Image" title="Image"></img>
</div>
<div id="tabs-3" class="content">
<p>Some other text</p>
</div>
</div>
<script>
$(function() {
$("#tabs").tabs();
});
</script>
http://jqueryui.com/demos/tabs/
Without knowing something about the company you were taking the test for its hard to say what they were looking for.
In general employers are not looking for perfect code but how you approach the problem. For example you could say that they were looking to see if you would follow their instructions blindly or stick to convention and good practices of adding external style/script references or just clean, standard compliant, concise code.
I am a complete novice so please don't take anything I say too seriously but I would of attempted to create some reusable concise code which would/could be reused and expanded very quickly and easily while being maintenance friendly (Just because its a text doesn't mean that you can forget about these things).
Just doing this very rough and off the top of my head but something like this:
$('#tab-menu').click(function(e) {
e.preventDefault();
clearContent();
$(this).show();
});
If it was for a company that were involved with mobile devices you would probably want to bind the events so you get the same functionality.
Something that I have always done is provided an assumptions document even just if its in notepad. Its always looked upon positively as it shows you are stopping and thinking about what you have to do instead of going gun ho.
Overall I think you did a good job! You have a great attitude and just learn from experiences like these, improve and get better! Today's juniors will be tomorrows experts! if we work hard enough
you don't need jQuery UI for this.
demo http://jsbin.com/atogil/2/edit
HTML
<div class="tabs">
<nav class="tab-btns">
tab btn 1
tab btn 2
tab btn 3
tab btn 4
</nav>
<div class="tab-contents">
<div id="tab1">tab content 1</div>
<div id="tab2">tab content 2</div>
<div id="tab3">tab content 3</div>
<div id="tab4">tab content 4</div>
</div>
</div>
JS
$.fn.myTabs = function(settings){
return this.each(function() {
/*
save cached version of the first elements inside the containers.
by calling the first elements of each container you are not limitng
the plugin user to any specific class or elememt.
*/
var btns = $(settings.nav, this).children(),
tabs = $(settings.tabs, this).children();
/*
we relying on the order of the elements as the conection between
the buttons and the tabs notice that .each() get the index of the btn..
we are useinf it to find the current tab.
*/
btns.each(function(index){
var btn = $(this),
tab = tabs.eq(index);
btn.click(function (e){
/* prevent unnesscry work by checking
if the button clicked is already active */
if(btn.is('.active')) return false;
/* notice that first filter to find the last 'active'
button before we remove the 'active' class otherwise it
remove the class for every button.
unnesscry work prevented again */
btns.filter('.active').removeClass('active');
/* hide previus tab.. */
tabs.filter(':visible').hide();
btn.addClass('active');
tab.show();
return false;
});
});
// emulate click on the first tab button;
btns.first().click();
});
};
and call your script like this;
$(function() {
$('.tabs').myTabs({
// container of navigation inside '.tabs'
nav : '.tab-btns',
// container of contents inside '.tabs'
tabs : '.tab-contents'
});
});

Jquery div expands all divs on page

<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".content").hide();
jQuery(".link").click(function()
{
jQuery("div.content").slideToggle(500);
});;
});
</script>
How to expand only the div which is linked to the specific link?
Edit:
Its done like this
<div class="comment">
<div class="bar">
<a class="link">#</a>
</div>
</div>
<div class="content">
<div class="comment">
<div class="bar">
<a class="link">#</a>
</div>
</div>
</div>
EDIT 2:
You changed your HTML. Now do this:
jQuery(this).closest('div.comment').next('div.content').slideToggle(500);
But wait! Now you have 2 different div.link elements in different relation to .content elements. Is this your actual HTML markup?
You could also do this:
jQuery(this).closest('div.content').slideToggle(500);
Please provide your actual HTML.
EDIT:
Based on updated question, do this:
jQuery(this).parents('div.blaat1').eq(1).next().slideToggle(500);
How to expand only the div which is linked to the specific link?
How are they linked?
If the div is a descendant, do this:
jQuery(this).find('div.content').slideToggle(500);
If the div is a an ancestor, do this:
jQuery(this).closest('div.content').slideToggle(500);
If the div is the next sibling, do this:
jQuery(this).next().slideToggle(500);
If the div is the previous sibling, do this:
jQuery(this).prev().slideToggle(500);
Without seeing your HTML structure, we can only guess at the solution.
For this HTML:
<div class="blaat1">
<div class="blaat1">
<a class="link">#</a>
</div>
<div class="blaat2">
<a class="link">#</a>
</div
</div>
<div class="content">
<div class="otherdivs">
<div class="blaat1_div"><p>Hi – I'm blaat 1</p></div>
<div class="blaat2_div"><p>Hi – I'm blaat 2</p></div>
</div>
</div>
Use this JS:
<script type="text/javascript">
$(document).ready(function() {
$(".content").hide();
$(".link").click(function() {
var blaat = $(this).parent().attr("class");
$(blaat+"_div").slideToggle(500);
});;
});
</script>
I haven't tested that, but it should work.
Try this:
$(".link").click(function(){
$(this).parents('div.content').slideToggle(500);
});;

Categories

Resources