Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS on HTML button click?

I want to modify the CSS of a page (hide elements of a certain class, "class") when a user clicks a button. I can't seem to find the correct JavaScript for getting this button to trigger the style change. I would prefer to avoid jQuery in my solution.

HTML:

<html>

<head>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <script type="text/javascript" src="content.js"></script>
</head>

<body>
    <p>hide "class"</p>
    <button type="button" onclick="hide_class()">hide class</button>
</body>

</html>

JavaScript:

function hide_class() {

    document.addEventListener("DOMSubtreeModified", function (event) {
        if (document.getElementsByClassName(".class")) {
            var x = document.querySelectorAll(".class");
            var i;
            for (i = 0; i < x.length; i++) {
                x[i].style.visibility = "hidden";
            }
        }
    });
}

Edit: Here is my manifest.json and background.js

Manifest.json (does not reference content.js):

{
"manifest_version": 2,

"name": "my extension",
"description": "it doesnt work",
"version": "0.1",
"background": {
"scripts": ["background.js"],
"persistent": false
 },

"permissions": [
"declarativeContent"
 ],

"page_action": {
    "default_popup": "popup.html"
    },  

 "icons" : { "16": "16.png",
          "48": "48.png",
          "128": "128.png" },

  }

Background.js:

chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([
  {
    conditions: [
      new chrome.declarativeContent.PageStateMatcher({
        pageUrl: { urlContains: 'g' }, //url contains g
      })
    ],
    actions: [ new chrome.declarativeContent.ShowPageAction() ]
  }
 ]);
 });
 });
like image 748
Nat Avatar asked Jun 03 '26 05:06

Nat


1 Answers

You could add an event listener to the element.

Example:

HTML

<div id="hide_me">
  I will hide if you click me
</div>

JS

document.getElementById('hide_me').addEventListener('click', function () {
  this.style.display = 'none';
});

Fiddle: https://jsfiddle.net/y1gc01zj/1

EDIT you could also add a css class:

CSS

.hide {
  display: none;
}

JS

document.getElementById('hide_me').addEventListener('click', function () {
    //  this.style.display = 'none';
  this.classList.add('hide')
});
like image 93
Baruch Avatar answered Jun 05 '26 17:06

Baruch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!