jQuery: Replace " " with normal spaces for window widths under 500px - javascript

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
}

Related

Store div status on page reload

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));
});
});

variable assignment not working

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

Changing links with JS

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;
}
}

Replace All Words In Document Body Doesn't Work

Firstly sorry for my english, i have code that doesnt work when I execute it on
<script language="javascript" src="/thecode.js"></script>
I put thecode.js on footer
var msg=document.body.innerHTML;
for(var i=0;i<msg.length;i++){
var tx=document.body[i].innerHTML;
tx=tx.replace(/dog/ig,'animal');
tx=tx.replace(/apple/ig,'fruit');
tx=tx.replace(/\[VIdEo\]/ig,'Video');
tx=tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com');
document.body.innerHTML=tx;}
I think i dont make any fault, but when i execute it, its doesnt work.
thank for your attention... :)
no need to iterate body element
try this:
want to change to with that js? i have used to make it
function addTitleToSurveyUrls() {
var elements = document.getElementsByTagName('a');
for(var el in elements) {
var element = elements[el];
var href = element.getAttribute("href");
if(href.indexOf('survey_')>-1) {
element.setAttribute('title', 'Some TITLE HERE');
}
}
}
function replaceBodyElements() {
var tx=document.body.innerHTML;
tx = tx.replace(/dog/ig,'animal');
tx = tx.replace(/apple/ig,'fruit');
tx = tx.replace(/\[VIdEo\]/ig,'Video');
tx = tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com');
document.body.innerHTML=tx;
}
window.onload = function(){
replaceBodyElements();
addTitleToSurveyUrls();
// ... some another operations
};
also
document.onreadystatechange = function () {
var state = document.readyState;
if(state == 'complete') {
replaceBodyElements();
addTitleToSurveyUrls();
}
}​
I've used onload event because maybe document has dynamic elements and etc. so better wait while all elements get loaded and change it.
or You can replace window.onload with window.document.onload

Line break character while looping through an array/function

Seemingly simple but I can't find the correct placement. I have the following function in my HTML head:
<script>
(function($) {
$.fn.writeText = function(content) {
var contentArray = content,
current = 0,
elem = this;
setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
}, 1000);
};
})(jQuery);
</script>
I call it in the body like:
<script>
// test getArray() method in external JS file
document.write(getArray());
$(document).ready(function($){
var contentArray = getArray();
$('#calculations').writeText(contentArray);
});
</script>
<h3>Fibonacci Sequence:</h3>
<p id='calculations'></p>
I can't find out where to place the '+ br /' to concatenate each writeText with a line break.
Using line breaks is a little amateur. Here's a script that appends paragraph tags.
$(function() {
var contentArray = ['first', 'second', 'third'],
iContent = 0;
function showContent() {
$('#calculations').append('<p>' + contentArray[iContent] + '</p>');
if (iContent < contentArray.length - 1) {
window.setTimeout(function () {showContent(); }, 1000);
iContent = iContent + 1;
}
}
window.setTimeout(function () {showContent(); }, 1000);
});
Also you don't need
$(document).ready(
A simple $( will do the same. Why are you doing a document.write() in your code? If you just want to see the array values a console.log() would work better.
I am taking a wild stab at what I think you are trying to do, but if I am correct, wouldn't this work?
$('#calculations').html(getArray().join('<br>'));
I would also not put JS in the head of your doc. Put it at the end the the body tag instead.

Categories