I have this code:
HTML
<div>
<p id="ui-id-1">Google</p>
</div>
Javascript
function myFunction() {
location.href="http://www.youtube.com";
if($(window).width() < 958){
document.getElementById("ui-id-1").innerHTML = location.href;
}
}
Is it possible to change the link in the <p> when the width is 958 or less?
You cannot set location.href where you are setting it. It immediately will load the page you set it to. Perhaps you meant
function myFunction() {
var loc="http://www.youtube.com";
if($(window).width() < 958){
$("#ui-id-1 a").attr("href",loc);
}
}
You do need to call the function when some event happens.
For example when loading the page (assuming of course that jQuery is loaded)
$(function() {
if($(window).width() < 958){
$("#ui-id-1 a").attr("href","http://www.youtube.com");
}
});
You might also wanna add a resize function to handle it.
function myFunction() {
var href = "http://www.youtube.com";
if ($(window).width() < 958) {
$("#ui-id-1 > a")[0].href = href;
}
}
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
}
I have multiple divs in one html page under common wrapper class.
I am using hide and show method on clicking next and previous option.
What I am trying to achieve: On page reload/refresh, the div which is showing currently should show after page reload.
So in short if you reload/refresh from pink screen, it should show same pink screen after page reload.
What I tried: I am storing the display properties (none or block) is local storage and on page reload trying to give same properties to divs again. Most of the responses and solution I checked in Stack overflow is regarding opening the same tab when refresh. but my case is what in same tab I have multiple div and I want to open from the same state which it was earlier.
Logic I used:
$(window).on('load', function(){
var disp = localStorage.getItem("disp");
var ustatus = JSON.parse(disp);
$(".chk").text(ustatus);
for (var x=ustatus; x<ustatus.length; x++){
$(".pg"+x).css("display", ustatus[x]);
}
});
This is fiddle link I tried:
Page reload demo JS Fiddle link
Your HTML and CSS code is perfect but you need to make corrections in your JavaScript code.
Observation 1 : You "for" loop to assign display style has problem with variable x. You need to assign integer value to x.
Observation 2 : You need to remove that "display" style from "div" elements when you click on "next" and "previous" links.
Hear is new Js fiddle link with updated code.
$(window).on('load', function () {
//localStorage.removeItem("disp");
var disp = localStorage.getItem("disp");
var ustatus = JSON.parse(disp);
$(".chk").text(ustatus);
for (var x = 1; x <= ustatus.length; x++) {
$(".pg" + x).css("display", ustatus[x-1]);
}
});
$(".next").on("click", function () {
$(this).parent().addClass("off").removeClass("on").removeAttr("style");
$(this).parent().next().addClass("on").removeClass("off").removeAttr("style");
});
$(".prev").on("click", function () {
$(this).parent().addClass("off").removeClass("on").removeAttr("style");
$(this).parent().prev().addClass("on").removeClass("off").removeAttr("style");
});
$(window).on('beforeunload', function () {
var display = $(".clr").map(function () {
return $(this).css("display");
}).get();
localStorage.setItem("disp", JSON.stringify(display));
});
You can also download this file. Please run index.html to see the output.
You don't really need the on class:
$(window).on('load', function(){
var disp = localStorage.getItem("disp");
var ustatus = JSON.parse(disp);
$(".chk").text(ustatus);
for (var x=0; x<ustatus.length; x++){
$(".pg"+(x+1)).toggleClass("off", ustatus[x]);
}
});
$(".next").on("click", function(){
$(this).parent().addClass("off");
$(this).parent().next().removeClass("off");
});
$(".prev").on("click", function(){
$(this).parent().addClass("off");
$(this).parent().prev().removeClass("off");
});
$(window).on('beforeunload', function(){
var display = $(".clr").map(function(){
return $(this).hasClass("off");
}).get();
localStorage.setItem("disp", JSON.stringify(display));
});
Fiddle
note: you can't use $(window).on('load', ...) in a fiddle - the JS in the editor is run on load
EDIT: you might also want to validate ustatus before applying it, something like
if (Array.isArray(ustatus) && ustatus.filter(x => x === true).length === 1) {
for (var x=0; x<ustatus.length; x++){
$(".pg"+(x+1)).toggleClass("off", ustatus[x]);
}
}
You can do it without using display, you can use on and off classes, i think that's why they are created for
$(window).on('load', function(){
var disp = localStorage.getItem("disp");
var ustatus = JSON.parse(disp);
if(ustatus!=undefined){
$(".chk").text(ustatus);
for (var x=1; x<=ustatus.length; x++){
if(ustatus[x-1]=='on'){
$(".pg"+x).addClass("on").removeClass("off");
}
else{
$(".pg"+x).addClass("off").removeClass("on");
}
}
}
$(".next").on("click", function(){
$(this).parent().addClass("off").removeClass("on");
$(this).parent().next().addClass("on").removeClass("off");
});
$(".prev").on("click", function(){
$(this).parent().addClass("off").removeClass("on");
$(this).parent().prev().addClass("on").removeClass("off");
});
$(window).on('beforeunload', function(){
var display = $(".clr").map(function(){
if($(this).hasClass('on'))
return 'on';
else
return 'off';
}).get();
localStorage.setItem("disp", JSON.stringify(display));
});
});
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
Hi i have started making this web.
I am desperately trying to make my menus to fly-in and out on transitions. I want my menus to fly-in in a certain order starting from top to bottom.
I have updated this question from its original.
html:
<div id="flyin">
<form action="WoodEnglish.html" method="get">
<input id="Wood" type="image" src="Wood.png" alt="Submit" >
</form>
</div>
javascript:
<script type="text/javascript">
$(document).ready(function () {
var currWidth = $(window).width();
console.log(currWidth);
var startPos = -1;
var endPos = 1000;
console.log(endPos);
$('#flyin').animate({left: endPos},1000);
$('#Wood, #submit2').click(function () {
if (this.id == 'Wood') {
$('#flyin').animate({left: endPos}, 1000);
}
else if (this.id == 'submit1') {
alert('Submit 2 clicked');
}
});
});
</script>
However there is still two problems with this code
is this; var currWidth = $(window).width(); i think. I need my buttons to fly into the screen from out of screen and atm i am not allowed to do that.
atm it doesn't wait until the animation is complete before loading the next html on action form.
thx in advance for any contributions
You have referenced items in the <head>, even before they are loaded. Please wrap everything in document ready function:
$(document).ready(function () {
var currWidth = $(window).width();
console.log(currWidth);
var startPos = -100;
var endPos = (currWidth / 2) + (startPos / 2);
console.log(endPos);
$('#flyin').animate({left: endPos}, 1000);
});
Fiddle: http://jsbin.com/pafigicabo/edit?js,output
Okay i figured it out. This will make an image fly from outside the screen to inside the screen and then again fly from inside the screen to outside the screen when you click it.
$(document).ready(function () {
$('#flyin').animate({left: "1000px"},1000);
$('#Wood, #submit2').click(function () {
if (this.id == 'Wood') {
$('#flyin').animate({left: "-1000px"}, 1000);
}
else if (this.id == 'submit1') {
alert('Submit 2 clicked');
}
});
});
My script contains a link a element with href attribute of "#login" as below.
Login
I want to my Javascript function detect the "href" element in the link and execute. How can I do this? My Javascript function is
window.onload = function() {
document.getElementsByTagName("a[href=#login]").onclick = function(e) {
e.preventDefault();
alert("working");
}
}
Why have I seen no querySelector love in these answers?
If you want to use that CSS selector to grab your link, nothing is stopping you:
window.onload = function() {
document.querySelector("a[href='#login']").onclick = function(e) {
e.preventDefault();
alert("working");
}
}
Login
EDIT:
I saw in another answer that you believe there may be multiple links on a page that match that selector, in which case you'll need to loop through them:
window.onload = function() {
var links = document.querySelectorAll("a[href='#login']"),
//always create anonymous functions outside of a loop :)
click = function(e) {
e.preventDefault();
alert("working");
}, i;
for (i = 0; i < links.length; i++) {
links[i].onclick = click;
}
}
Login
Login
Try this:
Login
function getValue()
{
alert("working");
e.preventDefault();
}
FIDDLE
Your getElementsByTagName is treating it like a jquery selector, which it is not designed to do.
It would be much simpler to give the tag an id and use getElementById:
window.onload = function() {
document.getElementById("loginLink").onclick = function(e) {
e.preventDefault();
alert("working");
}
}
Login
If for whatever reason you cannot change the html and you want to do it this way you would need to get all a tags then loop through each one to test the href attribute. Note you need to use a.getAttribute("href") to get "#login", rather than just a.href which oftens give you an full URL:
window.onload = function() {
var aTags = document.getElementsByTagName("a");
for(var i = 0; i < aTags.length; i++) {
var a = aTags[i];
if(a.getAttribute("href") == "#login") {
a.onclick = function(e) {
e.preventDefault();
alert("working");
}
}
}
}
Login
Test
Login Again