I do not understand why my variable assignment: var mn = $("nav"); is not working in this piece of code:
var mn = $("nav");
var randomNum = 23;
$(window).scroll(function() {
if( $(this).scrollTop() > 400 ) {
$("nav").addClass("main-nav-scroll");
alert(randomNum);
} else {
mn.removeClass("main-nav-scroll");
}
});
When I manually write it out in $("nav").addClass(...); it works perfectly. I thought the problem was maybe the scope of the variable so I added the randomNum variable to print out and it does so just fine. I'm really stumped. It took me forever to find this simple error So I'd like to understand for next time. Thanks.
Your problem is likely nav. It is a dom element just like <p>. So when you try to select it your query is to general.
Give nav and ID and select it that way.
For example
HTML
<nav id "foob"></nav>
JS
var mn = $("#foob");
In Addition
Also, put a console.log('scroll event fired') in your event handler so that you can verify that the event is actually firing.
This works:
<script type="text/javascript">
jQuery(document).ready(function ($selimatac) {
// öncelikle divi bir gizleyelim
$selimatac("#yukari").hide();
//scroll eğer 100 değerinin üstünde ise divi görünür yapacak, değilse gizleyecektir
$selimatac(function () {
$selimatac(window).scroll(function () {
if ($selimatac(this).scrollTop() > 100) {
$selimatac('#yukari').fadeIn();
} else {
$selimatac('#yukari').fadeOut();
}
});
// butona tıklayınca sayfa en üste çıkması için
$selimatac('div a').click(function () {
$selimatac('window,html,body').animate({
scrollTop: 0
}, 1000);
return false;
});
});
});
</script>
Look at http://selimatac.net/jquery-scrolltop-ile-yukari-cik-butonu/ for more information.
Maybe your var gets rewritten somewhere in your code. Try another var name
Related
I would like to replace all in my HTML files with normal spaces for window widths under 500px.
To do this, I started with this code:
window.onresize = xza;
window.onload = xza;
function xza() {
let window_size = window.matchMedia("(max-width: 500px)");
if (window_size.matches) {
$("document.documentElement").find(" ").replaceWith(" ");
} else {
// nothing should happen or it should be like it was before
}
Unfortunately, it doesn't work. Can someone help me please? :)
You need to keep in mind that isn't plain text. It's a special character (html entity). So to correctly replace it, you'll need to use unicode:
$(window).on("load resize", function(){
if($(window).width() < 500){
$("body").each(function() {
var text = $(this).text();
$(this).text(text.replace(/\u00a0/g, " "));
});
}
});
This will loop through each element inside <body/> and replace every with a normal space. Obviously I tested it before answering and it's working as expected.
You don't need to call an extra function. jQuery on load and on resize do the job.
Making your code to look for all in the whole page will put a very heavy processing load on the page. try reducing it to a specific div. In order to do that simply replace the $(document) with class name or id of the specific div. Example: $(".someClass")
$(window).on("load",function () {
if ($(window).width() < 500) {
$(document).text($(document).text().replace(/ /g, ' '));
console.log("Changing");
}
});
$(window).on("resize",function () {
if ($(window).width() < 500) {
$(document).text($(document).text().replace(/ /g, ' '));
console.log("Changing");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Bla bla bla bla</p>
Try using regex
window.onresize = xza;
window.onload = xza;
function xza() {
let window_size = window.matchMedia("(max-width: 500px)");
if (window_size.matches) {
let doc = $(document)
doc.text(doc.text().replace(/nbsp;/g, ' '))
} else {
// nothing should happen or it should be like it was before
}
This is my script -
my script alert when someone touch on any place on the page .
I am trying to execute alert only one time and not on every click.
This is the code i built which alert any time .
$( document ).ready(function() {
var click_count = 0;
if (click_count == 0){
$('body').click(function(){
alert();
var click_count = 1;
});
}
});
You have your if in the wrong place. You want it inside the click handler (the code that runs when the click occurs), not outside it. You also need to remove the var from var click_count = 1; so you 're using the one declared in the ready callback, not the one declared in the click handler:
$(document).ready(function() {
var click_count = 0;
$('body').on("click", function() {
if (click_count == 0) {
alert("Hi there");
click_count = 1;
}
});
});
Testing 1 2 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(Here's a runnable version for mobiles where Stack Snippets aren't rendered: http://output.jsbin.com/taropelopu)
But, rather than using click_count, I'd suggest removing the event handler after the first click. You could do that with off, but jQuery even has a function specifically for adding a handler you remove the first time it's called: one (rather than on):
$(document).ready(function() {
$('body').one("click", function() {
alert("Hi there");
});
});
Testing 1 2 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(Runnable version for devices where Stack Snippets don't render: http://output.jsbin.com/wivoroluzu)
With plain JavaScript you can do
let clicked = false;
const clickOnce = () => {
if (!clicked) {
alert('clicked');
clicked = true;
}
};
document.body.addEventListener('click', clickOnce);
some body content
And you don't even need a clicked variable to store the state. Just remove the event listener once it is triggered.
const clickOnce = () => {
alert('clicked');
document.body.removeEventListener('click', clickOnce)
};
document.body.addEventListener('click', clickOnce);
some body content
How do I manage that if the user scrolls down the mouse wheel or clicks on $('#next') it will execute the function below?
var wd = event.originalEvent.wheelDelta;
if (wd < 0 || $("#next").click(function() {}) {
if (status == 1 && $('body').scrollTop() == $("#b1").offset().top) {
$('body').animate({
scrollTop: $("#b2").offset().top
}, 900);
prev.style.display = "block";
b1Slide_b('b1');
b1Slide('b2');
status = 2;
}
Include the code you want executed in a function, and then initiate both event to point to that function:
function stuffToDo(){
// the stuff you want to do here
}
$("#next").click(function() {
stuffToDo();
}
$("#next").scroll(function() {
stuffToDo();
}
This is not the cleanest way but it will allow you to give custom parameters to your function depending on the event, if you need.
Hope it helps
try something like this with your code.
made and example : jsfiddle
function myFunc() {
$(".content").css({"background":"red"})
};
$(window).scroll(function(){
if($(window).scrollTop()>0) {
myFunc();
};
});
$(".trigger").click(function(){
myFunc();
});
you need to do 2 separate functions in which you callback your function .
in myFunc() you insert everything you want to happen on scroll or on click
in this case changing the background color
How can i get the current scrolling position of my browser?, i want to fire events base on page position.This is what I tried:
var scroll_position=document.viewport.getScrollOffsets();
window.onscroll = function (event) {
if(scroll_position>1000)
{
alert('xxxxxxxxxxx');
}
Assuming that you're always going to be testing with window, you can use window.scrollY:
window.onscroll = function (event)
{
if(this.scrollY > 1000)
{
alert('xxxxxxxxxxx');
}
}
jsFiddle Demo
Try with:
window.onscroll = function (event) {
if (window.scrollY > 1000) {
alert('xxxxxxxxxxx');
}
}
As hsz said, do
window.onscroll = function (event) {
var scroll_position = document.viewport.getScrollOffsets();
if (scroll_position > 1000)
{
alert('xxxxxxxxxxx');
}
}
The problem with your code:
var scroll_position=document.viewport.getScrollOffsets();
scroll_position is only set once, when the page loads - therefore it stays the same (probably 0) and the alert never comes up because scroll_position is less than 1000.
hsz put the statement that sets scroll_position into the window.onscroll function, so it is updated every time the page scrolls.
Context: On my product website I have a link for a Java webstart application (in several locations).
My goal: prevent users from double-clicking, i. e. only "fire" on first click, wait 3 secs before enabling the link again. On clicking, change the link image to something that signifies that the application is launching.
My solution works, except the image doesn't update reliably after clicking. The commented out debug output gives me the right content and the mouseover callbacks work correctly, too.
See it running here: http://www.auctober.de/beta/ (click the Button "jetzt starten").
BTW: if anybody has a better way of calling a function with a delay than that dummy-animate, let me know.
JavaScript:
<script type="text/javascript">
<!--
allowClick = true;
linkElements = "a[href='http://www.auctober.de/beta/?startjnlp=true&rand=1249026819']";
$(document).ready(function() {
$('#jnlpLink').mouseover(function() {
if ( allowClick ) {
setImage('images/jetzt_starten2.gif');
}
});
$('#jnlpLink').mouseout(function() {
if ( allowClick ) {
setImage('images/jetzt_starten.gif');
}
});
$(linkElements).click(function(evt) {
if ( ! allowClick ) {
evt.preventDefault();
}
else {
setAllowClick(false);
var altContent = $('#jnlpLink').attr('altContent');
var oldContent = $('#launchImg').attr('src');
setImage(altContent);
$(this).animate({opacity: 1.0}, 3000, "", function() {
setAllowClick(true);
setImage(oldContent);
});
}
});
});
function setAllowClick(flag) {
allowClick = flag;
}
function setImage(imgSrc) {
//$('#debug').html("img:"+imgSrc);
$('#launchImg').attr('src', imgSrc);
}
//-->
</script>
A delay can be achieved with the setTimeout function
setTimeout(function() { alert('something')}, 3000);//3 secs
And for your src problem, try:
$('#launchImg')[0].src = imgSrc;
Check out the BlockUI plug-in. Sounds like it could be what you're looking for.
You'll find a nice demo here.
...or just use:
$(this).animate({opacity: '1'}, 1000);
wherever you want in your code, where $(this) is something that is already at opacity=1...which means everything seemingly pauses for one second. I use this all the time.
Add this variable at the top of your script:
var timer;
Implement this function:
function setFlagAndImage(flag) {
setAllowClick(flag);
setImage();
}
And then replace the dummy animation with:
timer = window.setTimeout(function() { setFlagAndImage(true); }, 3000);
If something else then happens and you want to stop the timer, you can just call:
window.clearTimeout(timer);