最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Hide div on specific url with css or js - Stack Overflow

programmeradmin0浏览0评论

I'm trying to hide a .sidebar-item on a specific link. I am using Laravel & Bootstrap.

I can hide it with CSS like so:

.sidebar-item {
display: none;

}

But that hides it everywhere and I only want it hidden on a specific url.

How can I hide it with CSS/JS?

I'm trying to hide a .sidebar-item on a specific link. I am using Laravel & Bootstrap.

I can hide it with CSS like so:

.sidebar-item {
display: none;

}

But that hides it everywhere and I only want it hidden on a specific url.

How can I hide it with CSS/JS?

Share Improve this question edited Apr 30, 2017 at 17:21 user4396006 asked Apr 30, 2017 at 11:40 LucicheLuciche 631 gold badge1 silver badge11 bronze badges 2
  • 1 You won't be able to do this with only CSS since it is not aware of where it is being used. The usual solution would be to serve a different CSS file for that specific URL or have some javascript code that hides these elements dynamically after the content has been loaded from the server. – Lix Commented Apr 30, 2017 at 11:48
  • Why not just avoid outputting the item entirely on that page. @if(!Request::is('your/url') in the Blade template. – ceejayoz Commented Apr 30, 2017 at 11:53
Add a ment  | 

2 Answers 2

Reset to default 2

There are a few ways you can achieve this using CSS and JavaScript. A simple way would be to check the URL of the page:

With jQuery:

document.ready(function() {
  if (window.location.href.indexOf('/my/url')) {
    //Hide the element.
    jQuery('.sidebar-item').hide();
  }
});

Without jQuery:

window.onload = function() {
  if (window.location.href.indexOf('/my/url')) {
    //Hide the element.
    document.querySelectorAll('.sidebar-item')[0].style.display = 'none';
  }
};

Alternatively, you could add a custom class to the body tag for each page in Laravel. This will allow you to customize specific pages using CSS. I'm not a Laravel developer, but you can see two examples here: http://dev-notes.eu/2016/10/add-body-class-on-laravel-views/

(following is reproduced from the above blog post)

First method:

Pass a relevant variable from the blade template:

{{-- /views/articles/index.blade.php --}}
...
@extends('layouts.master', ['body_class' => 'articles index'])
...

Then in /views/layouts/master.blade.php:

<body
  @unless(empty($body_class))
    class="{{$body_class}}"
  @endunless
  >

Second method:

In the child blade template:

@section('pageClass', 'js-home-page')

In the master:

<body class="@yield('pageClass')">

Let's say you added the 'my-custom-page' class to the body tag of the page you want .sidebar-item to be hidden on. You can then modify your CSS to the following:

.my-custom-page .sidebar-item {
  display: none;
}

A partial solution for assigning CSS properties based on current page url might be using CSS :target pseudo selector.

发布评论

评论列表(0)

  1. 暂无评论