hover menu jquery slide up and down too fast - javascript

i made this hover menu but is buggy
this my jquery code
$("#right_side li").mouseenter(function(e) {
$(this).children('ul').stop(true,true).slideDown();
});
$(this).stop();
$("#right_side li").mouseleave(function(e) {
$(this).children('ul').stop(true,true).slideUp();
});
and this my php code
function menu($li)
{
echo "<ul class='hovermenu'>";
$result = mysqli_query($li, "SELECT * FROM `categories` WHERE 1") or die(mysqli_error($li));
while ($Row = mysqli_fetch_array($result)) {
echo "<li class='cat'><div class='cat_div' ><a href='index.php?cat=".$Row['catid']."'>" . $Row['catname'] . "</a></div><ul class='sub'>";
$result2 = mysqli_query($li, "SELECT * FROM `brand` WHERE catid=".$Row['catid']."") or die(mysqli_error($li));
while ($Row2 = mysqli_fetch_array($result2)) {
echo "<li><a href='index.php?brand=".$Row2['id']."&cat=".$Row['catid']."'>" . $Row2['name'] . "</a></li>";
}
echo"</ul></li>";
}
echo "</ul>";
}
my problem is
when my mouseleave
and i mousein too fast
my menu sliding up and down too fast
please help meeeee!!!

Add the speed to your slideUp call e.g. "slow"
slideUp("slow")
You can also use a value in milliseconds.

you may simply add a time in milliseconds like slideUp(1000) or slideDown(300) or slideDown("fast") or slideUp("slow")
Hope this helps.

Can you change your script to this one and let me know if the issue is fixed
$("#right_side li").on({
mouseenter: function(){
$(this).children('ul').stop().slideDown();
},
mouseleave: function(){
$(this).children('ul').stop().slideUp();
}
});

There is a known issue with the jQuery slideUp/slideDown functions when the element being slid up/down has no set height. Ensure the element to be hidden has a specified height.
ALSO, the min-height css property will mess things up. Remove min-height from the element.
Reference:
https://forum.jquery.com/topic/slideup-slow-and-slidedown-slow-happening-instantly

Related

Font is not loaded beforehand when loading Ajax content into div (Wordpress)

I'm using a JS function in Wordpress with Ajax that loads content of a post in a modal div when certain elements are clicked. The JS function looks like this:
function openProjectModal($that) {
var post_id = $that.attr("rel");
window.location.hash = $that.data("slug");
$("#content-projects").load(localization.ajax_url+"?action=load_more_post&pid="+post_id,{},function(data,status){
initImageLoad();
});
}
The function that creates the markup in functions.php looks like this:
function load_more_post_callback() {
if( isset($_GET["pid"]) ){
$post = get_post( $_GET["pid"] );
if( $post instanceof WP_Post ) {
echo '<div id="close"></div>';
echo '<section id="title-projects"><h1>' . get_the_title($post->ID) . '</h1><p class="project-meta">' . get_field("location", $post->ID) . ' (' . get_field("year", $post->ID) . ')</p></section>';
} else {
// nothing found with the post id
}
} else {
// no post id
}
wp_die();
}
The h1 in the new content has a font applied to it through CSS that isn't used on the initial page. So when the div gets loaded with the content from the Ajax call, there is a delay in the loading of the font, which looks weird. It goes from blank, to Times New Roman, to the right font. When I close the modal and open a new one, the font is instantly loaded like it should be. I guess that it gets cached from the first load.
I've added the fonts in the CSS that is being used on the whole site, but it seems like the browser only loads the fonts that are actually being used in the markup, since this font that is unique for the Ajax content gets loaded when the Ajax content gets loaded.
I've only noticed this in Safari though, but it would be nice if there was a workaround for this even if it's just a special issue in Safari. Any ideas on how to preload the font before it's shown?
In your modal simply do
<h2 class="myTitleFont">Title</h2>
Then in css you can do:
.myTitleFont {
font-family. "yourFont";
}
or if really you have to:
.myTitleFont {
font-family: "yourFont" !important;
}
Obviously "yourFont" is the name of your font.
I still believe is just a css issue, however, create a callback for your modal when it is opened and run:
$(".modal").on.("show", function(){
addGoogleFont();
});
function addGoogleFont() {
$("head").append("<link href='https://fonts.googleapis.com/css?family=" + FontName + "' rel='stylesheet' type='text/css'>");
$(".modal h2").css("opacity", "1");
}
And set your modal h2 to opacity 0 so you won't see it until
.modal h2 {
opacity: 0;
}

Concatenation of selector with dynamic value not working - Jquery

I am trying to remove the style of my a href background. The issue is when I concatenate dynamic id with selector then it don't work. But when I use complete name of selector, then it works.
I know you can mark my question as duplicate like here but they are not working for me. Please correct me.
What Works:
$("a").click(function(event)
{
var id = event.target.id;
$('#chatIdStyle4').removeAttr("style");
});
What Didn't:
$("a").click(function(event)
{
var id = event.target.id;
$('#chatIdStyle'+id).removeAttr("style");
});
OR
$("a").click(function(event) {
//alert(event.target.id);
var iddds = event.target.id;
$('#chatIdStyle["'+ iddds + '"]').removeAttr("style");
});
NOTE: var id contains the dynamic id of event fired.
EDIT as asked:
Below is my HTML+PHP code. So, what it does is actually creates 4 dynamic a href with dynamic id. What I
want is when a specific a href gets clicked then it should remove previous a href background and
add background to the clicked a href.
<?php
$color = false;
$PID = 4;
for($i=0;$i<4;$i++)
{
?>
<a <?php if($color==true)
{
?> style="background-color: #E6E6E6;" <?php
}
$color=false;
?>
id="chatIdStyle<?php echo $PID; ?>"
href="#">
</a>
<?php
}
?>
I suggest using CSS solution instead of jQuery:
a { background: none; }
a:active { background: #E6E6E6; }
The second line will set the background for the last clicked a element.
About the :active pseudo class: https://www.w3schools.com/cssref/sel_active.asp

How can I execute javascript in this PHP loop?

I'm trying to generate random div widths for each database result that's output.
The code works when it's outside the loop, but every div is the same 'random' width.
load page and all divs are 200px
refresh page and all divs are 150px
refresh page and all divs are 250px ...etc.
The trouble being, I need each individual div to be a random width, not all the same random width... for that reason I've added my javascript inside the loop in order to get a new 'random' width each time a database value is output.
And of course, it's not working!
<?php
$result = mysql_query("SELECT * from tbl_status ORDER BY tbl_status.date desc");
while($row = mysql_fetch_array($result))
{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var x = Math.floor((Math.random()*150)+150);
$('.statusCont').width(x+'px');
});
</script>
echo'
<div class="statusCont">
<div class="statusUsr">Tom Adams - Newcastle</div>
<div class="statusTxt"><p>' . $row['status'] . '</p></div>
</div><!-- ends .statusCont -->
';}
?>
The reason that all the div's have the same random width is because the jquery class selector $('.statusCont') will return all elements with that class. So when your loop prints out the last selector it applies to all of the previous loaded elements.
Instead of including the javascript in the php while loop you can just write a script in the head that will affect the page after it's loaded
$(document).ready(function () {
$('.statusCont').each(function () {
var x = Math.floor((Math.random() * 150) + 150);
$(this).width(x);
});
);

Please help me with this smooth floating scroll

Well, I have this navigation menu which is static but I want to make it flow smoothly whenever user scrolls his page down or up... Please help with the code because I already have tried to do something but everything went bad.
Code:
<div id="menu">
<ul>
<li class="page_item">
Home
</li>
<?php wp_list_pages('&title_li=&exclude=6386'); ?>
<?php
if(is_user_logged_in() && !current_user_can('subscriber')) :
?>
<li class="page_item">
Tasks
</li>
<?php
endif;
?>
<?php
if(!is_user_logged_in()) :
?>
<li class="page_item">
Log in
</li>
<?php
endif;
?>
</ul>
</div>
I want this whole thing to float, how am I supposed to do this?
I tried to add this script and give menu class="scroller":
$(window).load(function(){
$(window).scroll(function(){
if($(window).scrollTop()>60){
$('.scroller').css('position', 'fixed');
$('.scroller').css('top', 0);
} else {
$('.scroller').css('position', 'relative');
$('.scroller').css('top', 60);
}
});
});
But no luck..
First of all, because you're using jQuery, you don't have to bind the onLoad event to do it. Just bind the onDomReady pseudo-event, without to create any other class (you already have the ID). That said, you need to listen for the onScroll event of the document. Try this:
$(function(){
$(document).on('scroll',function(){
var $this = $(this),
$menu = $('#menu'),
scrl = $this.scrollTop(),
menuHeight = $menu.height();
if( scrl > menuHeight ) {
$('#menu').css({
'position': 'fixed',
'top': 0
});
} else {
$('#menu').css({
'position': 'relative',
'top': menuHeight
});
}
});
});
This should works fine for your needs.
Here's a jsFiddle to test the code.
EDIT: code updated to dynamically handle every menu height.
The CSS property 'top' doesn't work with relative positioning. Try absolute instead.
$(window).scroll(function(){
if($(window).scrollTop()>60){
$('.scroller').css('position', 'fixed');
$('.scroller').css('top', 0);
} else {
$('.scroller').css('position', 'absolute');
$('.scroller').css('top', 60);
}
});
EDIT : You'll need to add a margin to the element above or below where you want the scrollbar to appear to create a gap for it.

jQuery Image fadeIn Upon Scroll Inside DIV

I can't get the actually LazyLoad plugin to work for me so I am trying to write my own with. Currently I have a list of images loading inside of a DIV. They are pulled by a PHP query to the mysql database. The DIV scroll is set to auto. The code I am using is:
<div id="b1" style="overflow:auto;">
<?PHP $result = mysql_query("SELECT * FROM images");
while($row = mysql_fetch_assoc($result)) {
echo "<img src='$row[photo]' style='display:none'> <br>";
}
</div>
<script type="text/javascript">
function imgCheck() {
var position = $("img").offset().top;
var scrollCheck = $("#b1").scrollTop() + $("#b1").height();
if ( scrollCheck > position) {
$("img").fadeIn("fast");
}
$("#b1").scroll( function() { imgCheck() } );
</script>
Although this is not quite working for me. Could anyone help me out or shoot out some suggestions?
A couple of things:
As the others have already said, your code has syntax errors - both with the PHP and the Javascript.
If you use display: none, the elements will not take up any height, thus causing the entire thing to become unscrollable and fail.
The first few elements should be visible without the user having to start scrolling
Taking these into consideration, we can try writing this this way:
// Cache the containing element and it's height
var b1 = $('#b1'),
h = b1.height();
// Insert 20 img's - simulating server-side code
for(var i = 0; i < 20; i++){
$('<img />', {
src: 'http://placehold.it/100x100',
alt: '',
class: 'hidden',
width: 100,
height: 100
// visibility: hidden to retain it's size
}).css('visibility', 'hidden').appendTo(b1);
}
b1.scroll(function(){
// Loop through only hidden images
$('img.hidden').each(function(){
// $(this).position().top calculates the offset to the parent
// So scrolling is already taken care of here
if(h > $(this).position().top){
// Remove class, set visibility back to visible,
// then hide and fade in image
$(this).css('visibility', 'visible')
.hide()
.removeClass('hidden')
.fadeIn(300);
} else {
// No need to check the rest - everything below this image
// will always evaluate to false - so we exit out of the each loop
return false;
}
});
// Trigger once to show the first few images
}).trigger('scroll');
See a demo of this here: http://jsfiddle.net/yijiang/eXSXm/2
If all of the images are hidden, then there will never be a 'scroll' even called as the element will never scroll.
What exactly are you trying to achieve? If it is to have new images that weren't previously visible, but now may be, become visible then you will have to do something like;
<div id="b1" style="overflow:auto;">
<?php $result = mysql_query("SELECT * FROM images");
while($row = mysql_fetch_assoc($result)) {
echo "<img src='$row[photo]' style='visibility:hidden'> <br>";
} ?>
</div>
<script type="text/javascript">
function imgCheck() {
var scrollCheck = $("#b1").scrollTop() + $("#b1").height();
$("#b1 img").each(function() {
var position = $(this).offset().top;
if (scrollCheck > position) {
$(this).fadeIn("fast");
}
});
}
$(document).ready(imgCheck);
$("#b1").scroll(imgCheck);
</script>
Note that I haven't tested the above, and I can imagine that it will result in all images being shown immediately, since all of their 'top's will be 0 due to them all being hidden and not having their position effected by previous images in the DOM.
Edit
I've changed the code above so the img's have visibility:hidden, which should give them a height and take up space in the DOM
I've been testing it, it seems to work with some modifications:
http://jsfiddle.net/antiflu/zEHtu/
Some things I had to change:
I added the closing } for the imgCheck() function, you forgot it
Some items need to be visible from the beginning on, otherwise the scrollbar never appears and imgCheck() is never called.
OK the problem with the above was that the images don't fade in separately upon scroll. I got it to work though with some modifications:
http://jsfiddle.net/antiflu/GdzmQ/
What I changed:
I changed the display: none to opacity: 0 so that any invisible picture has at least an empty placeholder of the same size, so that the scroll bar will be visible.
I then fade in using animate to opacity: 1
I used jQuery each() to iterate over the images and check for each of them if they should or should not be faded in (instead of checking for all, like before).
I wrapped the images in DIV's. I don't think it's necessary, but it doesn't harm either.
I tagged each image with an id, so that I can single them out for the fadein.
There are still some esthetic issues but this should help you on your way.

Categories