How to show and hide DIV based on URL. in Javascript - javascript

I have two URL's
url 1 = www.xyz.co.uk/asd.qmd
url 2 = www.xyz.co.uk/asd.qmd?getstep=4#
I want to show a div(left) when PAGE URL is www.xyz.co.uk/asd.qmd?getstep=4#
In the page form.php I wrote the following code:
<script>
$(function(){
var locate = window.location;
if (locate=="http://localhost/school/form.php") {
$('#left').hide();
} else {
$('#left').show();
}
});
</script>
<body onload="function()">
<div id="left">
aasdsasdfdsgfg
</div>
</body>
Why is this not working?

Just make php condition
<?php
if($_GET['getstep']){
}
?>

$('#left').toggle(window.location.href !== "http://localhost/school/form.php");

You need to make a show/hide function the proper javascript way. What you are doing at first with the (I assume) jQuery is beyond me - just declare a simple function containing the code you already have to show/hide and attach it to the onload-event.

If you just want to hide the div when the query string is empty, you could use the search property of the window.location object:
$(function(){
if (window.location.search === "") {
$('#left').hide();
} else {
$('#left').show();
}
});
Anything more complicated (i.e. a different div for each page value) and I recommend you look at regex

You need to use the href property of the window.location object.
var locate = window.location.href,
myElement = $('#left');
locate == "http://localhost/school/form.php"
? myElement.show()
: myElement.hide();

Related

Using an attribute value to add custom links for each images in my wordpres gallery

I'm using Elementor Pro for my photography website and i want to set custom links for each image in the gallery. By default, i can only set a global link which is the same for each image so that's not great.
In fact, i want to set a custom link which will redirect the user to the shop page of the specific image.
I found some code online (thanks to elementhow !) and it's really close to what i want, but i still need to change some things. The thing is a have to manually write all the links in an array and it's not convenient (close to 100 files and growing, if i change the order, i have to reorder the links, etc).
Here's the code i currently use :
<style>.e-gallery-item{cursor: pointer;} </style>
<script>
document.addEventListener('DOMContentLoaded', function () {
var filteredImages = document.querySelectorAll('.e-gallery-item');
//Edit the links HERE
var links = [
'https://www.mywebsiteurl.com/product/product-name1/',
'https://www.mywebsiteurl.com/product/product-name2/',
'https://www.mywebsiteurl.com/product/product-name3/',
'https://www.mywebsiteurl.com/product/product-name4/',
];
var _loope = function _loope(i) {
filteredImages[i].addEventListener('click', function () {
location = links[i];
});
};
for (var i = 0; i < filteredImages.length; i++) {
_loope(i);
}
});
</script>
I would like to use an attribute value in the algorithm to generate the link automatically for each image. I have the process in my mind, but i don't know how to code this...
Here's the code of one image ,i can set what value i want in "alt".
<div class="e-gallery-image elementor-gallery-item__image e-gallery-image-loaded" data-thumbnail="......" data-width="1024" data-height="768" alt="product-name";"></div>
I would like to use the "alt" attribute to create a unique url for each file, with this format :
'https://www......com/product/product-name/'
"product-name' will take the value of the "alt" attribute of each image.
I tried to change this part of the code (replace "links[i]" by trying to get the attribute value using filteredImages[i].getAttributes) but without success...
var _loope = function _loope(i) {
filteredImages[i].addEventListener('click', function () {
location = links[i];
});
};
Can someone give me some tips about how to do that ? I spend 2 years without coding so i'm a bit rusty...
I think this does what you'd like it to, as you have already done you can cycle through each image link using a class.
You can get the value of alt using the .attr() function and then replace the href value of the link.
DEMO
// Cycle through each image using common class
$(".e-gallery-image").each( function() {
// Get value of 'alt' for clicked item
alt = $(this).attr("alt");
// Update href value
$(this).attr("href", "https://www.mywebsiteurl.com/product/" + alt );
});
// Prove that its worked
$(".e-gallery-image").click( function() {
// Confirm all is correct
console.log($(this).attr("href"));
// Assign url to window
location.href = $(this).attr("href");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="e-gallery-image" href="test.com" alt="product1">Product 1</div>
<div class="e-gallery-image" href="test.com" alt="product2">Product 2</div>
<div class="e-gallery-image" href="test.com" alt="product3">Product 3</div>
<div class="e-gallery-image" href="test.com" alt="product4">Product 4</div>
<div class="e-gallery-image" href="test.com" alt="product5">Product 5</div>
In fact it was really simple. I tried to target a parent element and it worked ! If anyone is interested, here's the code i use :
document.addEventListener('DOMContentLoaded', function () {
var filteredImages = document.querySelectorAll('YOUR_SELECTOR');
var _loope = function _loope(i) {
filteredImages[i].addEventListener('click', function() {
location = "YOUR_WEBSITE_URL" + filteredImages[i].querySelector("YOUR_SELECTOR").getAttribute("alt");
});
};
for (var i = 0; i < filteredImages.length; i++) {
_loope(i);
}
});

Access html of loaded html page in div

Hi assuming I have a main.js and I have the following code:
$("#mirador").load("mirador.html");
that loads the html in index.html
<div id="mirador"></div>
Is there any way I can change the innerHTML of mirador.html elements by id from main.js?
I was thinking soemthing along these lines:
$("#placeholder").load("b.xhtml #id2", function(){
var myTemp = document.querySelector("#id2");
if (myTemp) {
alert(myTemp.innerHTML);
} else {
alert("#id2 is undefined");
};
});
but I don't want to alert but change the content ex:
myTemp.innerHTML = "abc";
Note : id should be unique
$("#mirador").load("mirador.html",()=>{
$("#mirador").find("#id2").html("abc")
});
If you have non-unique id's use this
$("#mirador").load("mirador.html",()=>{
$("#mirador").find("#id2").each(function(e){
$(this).html("abc")
})
});

How to keep the selected menu active using jquery, when the user comes back to page?

I have a typical menu structure -
<Ul class="nav">
<li>Menu1</li>
<li>menu2</li>
-------
</ul>
When I click on certain menu, as per my jquery written on load of layout.html, it selects particular menu.
<script>
jQuery(function(){
jQuery('.nav>li>a').each(function(){
if(this.href.trim() == window.location)
$(this).addClass("selected");
});
</script>
But on that page if I click on certain link which takes me on some other page and then when I come back the menu item does not remain selected.
How can I modify my jquery to achieve this?
Thanks in advance !
As SJ-B is saying, HTML5 Web Storage is a good solution.
If you don't intend to click more than one or two pages away from the page with your list menu, you could add a query to the link that takes you away form the page e.g. the id of one of your list menus.
href="somepage.html could become something like this href="somepage.html?menu_id=menu5
When using window.history.back(), you could then fish the id out of the URL using window.location.search and use id to select the list menu.
You can use simple css code. Use active attribute like
a:active
{
//Some style
}
You can use below code to achieve this.
var lastele=siteurl.substring(siteurl.lastIndexOf("/")+1);
jQuery(".nav>li> a").each(function(){
var anchorhref=jQuery(this).attr("href");
var finalhref=anchorhref.substring(anchorhref.lastIndexOf("/")+1);
if(finalhref==lastele){
jQuery(this).addClass("selected");
}
});
I would do something like this :
<ul class="nav">
<li id="home">Home</li>
<li id="contact">Contact</li>
</ul>
Javascript :
// http://mywebsite.com#home
// location.hash === '#home'
jQuery('.nav ' + location.hash).addClass('selected');
Try to use Session Object of HTML5.
sessionStorage.varName = id of selected item.
on load just check if the sessionStorage.varName has value or undefined, if not then get the value
`var value = sessionStorage.varName;` and set it.
Well there could be many ways, on which is this which i like and always use:
It works when you path name is same as your link name For e.g. yourwebsite.com/Menu1
function setNavigation() {
var n = window.location.pathname,t;
n = n.replace("/", "");
t = $("ul li:contains(" + n + ")");
t.addClass("active");
}
You can than define styling in your active class as you like.
I stumbled upon this when googling for something similar. I have a JQueryUI accordion menu. My menu is in an included script (classic asp), so it is on every page but I think it is a similar situation. I cobbled something together based on SJ-B's answer (don't know why it was down voted).
I have this:
function saveSession(id) {
if (window.sessionStorage) {
sessionStorage.activeMenu = $("#jqmenu").accordion("option", "active") ;
sessionStorage.activeLink = id ;
}
}
and this
$(function() {
//give every li in the menu a unique id
$('#jqmenu a').attr('id', function(i) {
return 'link'+(i+1);
});
var activeMenu = 0;
var activeLink = "";
if (window.sessionStorage) {
activeMenu = parseInt(sessionStorage.activeMenu);
activeLink = sessionStorage.activeLink;
}
$("#" + activeLink).parent().addClass("selectedmenu");
$("#jqmenu").accordion({collapsible: true, active: activeMenu, heightStyle: "content", header: "h3"});
$("#jqmenu a").click(function() { saveSession($(this).attr('id')); });
});
OK, a bit untidy and cobbled together from various suggestions (I'm still learning), but it seems to work. Tried on IE11 and Firefox. Chrome can't find localhost but that's another story.
add lines below
<script>
$(function(){
$("a[href='"+window.location+"']").addClass("selected");
});
</script>
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('.nav li').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});

Showing/hiding div onload

So I have a class of div's that i want to be shown or hidden depending on a variable i get.
I have this code:
**HTML**
<div class="div_estado" >
testing that
</div>
<div class="div_estado" >
testing this
</div>
**JS**
$(document).ready(function(){
var estado= 4; //instead of 4 i have "<?php echo $_GET['estado']; ?>" but let's supose its' value is 4
if (parseInt(estado)==5)
{
$('.div_estado').show; // not working
}
else {
$('.div_estado').hide; // not working
}
});
However it doesn't work properly, can you help me solve this?
DEMO
hide and show are methods, not properties. The syntax for invoking a JavaScript function requires a set of parentheses after the function name.
$('.div_estado').show();
$('.div_estado').hide();
Updated JSFiddle
FIDDLE
You should use "show()" and not just "show". Check the jQuery API info here.
$(document).ready(function(){
var estado= 4; //instead of 4 i have "<?php echo $_GET['estado']; ?>" but let's supose its' value is 4
if (parseInt(estado)==5)
{
$('.div_estado').show(); // not working
}
else {
$('.div_estado').hide(); // not working
}
});
You are forgetting () . It is a function not a property. Please change it to...
$('.div_estado').show();
...
$('.div_estado').hide();
You are simply missing brackets, it is show() and hide().
Use CSS to hide div
div.radio {
display:none;
}
IN JS Show div on load
$(document).ready(function () {
$('div_estado').show();
});

How write this in javascript

I have problems for insert dynamic id into function of JavaScript the code:
$('#scroll-up1, #scroll-down1').bind({ ..............
In this example I need the function to take values of id I send across the function
$('#scroll-up+id, #scroll-down+id').bind({ ..............
The problem it´s the quotes as " or ' no works for me and I can´t use right for function works fine , this script let me scroll text ok but only problem with this because no let me send values right from id of function.
EDIT FOR ME FOR PUT ALL CODE : .....
PHP AND HTML CODE
<?php
$fil_comments=file("comments.txt");
for ($i=0;$i<sizeof($fil_comments);$i++)
{
$line=explode("~",$fil_comments[$i]);
if ($i%2==0)
{
$back=1;
}
else
{
$back=2;
}
?>
<li>
<div id="web_comment_<?php echo $back?>">
<div id="web_comment_name"><?php echo $line[0];?></div>
<div class="web_comment_texto" id="scroll<?php echo $i;?>"><?php echo $line[1];?></div>
<div class="web_comment_arrow" style="margin-left:260px;" id="scroll-down<?php echo $i;?>"><img src="imagenes/comments/arrow_up.png"></div>
<div class="web_comment_arrow" style="margin-left:288px;" id="scroll-up<?php echo $i;?>"><img src="imagenes/comments/arrow_down.png"></div>
</div>
</li>
<script>
scroll_diver(<?php echo $i;?>);
</script>
<?
}
?>
FUNCTION OF JAVASCRIPT CODE
<script type="text/javascript">
function scroll_diver(id)
{
$(function() {
var ele = $('#scroll'+id);
var speed = 30, scroll = 5, scrolling;
$('#scroll-up'+id).mouseenter(function() {
// Scroll the element up
scrolling = window.setInterval(function() {
ele.scrollTop( ele.scrollTop() - scroll );
}, speed);
});
$('#scroll-down'+id).mouseenter(function() {
// Scroll the element down
scrolling = window.setInterval(function() {
ele.scrollTop( ele.scrollTop() + scroll );
}, speed);
});
//var a='#scroll-up'+id;
//var b='#scroll-down'+id;
var a='#scroll-up'+id;
var b='#scroll-down'+id;
//$('a,b').bind({
//$('#scroll-up1, #scroll-down1').bind({
//$('#scroll-up'+id+',#scroll-down'+id)
/// THE PROBLEM HERE !!!
$('#scroll-up'+id+', #scroll-down '+id).bind({
click: function(e) {
// Prevent the default click action
e.preventDefault();
},
mouseleave: function() {
if (scrolling) {
window.clearInterval(scrolling);
scrolling = false;
}
}
});
});
}
</script>
Basically the problem it´s in the line of JavaScript function for send id, if you see the PHP code, I use bucle for for create scrolling tips with informations and in each I can scroll his content, for this I call function into the bucle with:
<script>
scroll_diver(<?php echo $i;?>);
</script>
But in this line no send right information for works ok, if I use out bucle for one specific id, works ok , with this works yes but scroll up and down crazy fast , and the controls no works fine.
Then you need to look at something like this:
$('#scroll-up' + id + ', #scroll-down' + id).bind({ ..............
As a commentor mentioned, jQuery selectors are simply strings. You can put them together as you see fit. In this case, I'm concatenating the id (which for simplest examples, I'm assuming is a number or other unique identifier) to the #scroll-up selector, so if your id was "1", you would end up with a string, effectively, that looks like:
'#scroll-up1, #scroll-down1'
after the string concatenation occurs.
Also, it might be worth noting that you'd probably get better bang for your buck if you simply gave both objects the same class, then inside your binding function, work out which item called and perform your scrolling appropriately.
So, if you had:
<div class="container">
<div id="scroll-up1" class="scroller"><!-- and code --></div>
<div id="scroll-down1" class="scroller"><!-- and code --></div>
</div>
then your javascript could look like this, avoiding the need for concatenation:
$('.container').on("mouseover",'.scroller', function(){
var thisId = $(this).attr("id");
if(thisId == "scroll-up1"){
// do your up-scroll
} else if(thisId == "scroll-down1") {
// do your down-scroll
}
});
Mind you, that uses .on(), which is preferred over .bind(), but the idea is to handle it based on a common class, rather than having to modify your selector every time you go to bind your event handler for those items.
Recommended solution: use CLASS NAMES for COMMON FEATURES
$('.scroll-up, .scroll-down').bind({
or even:
$('.scroll').bind({
var id = 38;
$('#scroll-up' + id + ', #scroll-down' + id).bind({ ..............

Categories

Resources